我有它包装一个RESTful API的资源。我使用的资源从我的控制器来创建新的对象,并将其保存,类似于从角文档这个片段:
I have a resource which wraps a RESTful API. I use that resource from my controller to create new objects and save them, similar to this snippet from the Angular docs:
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
当写入茉莉花一个单元测试,我得到以下错误执行$保存呼叫时:无法读取属性未定义'$承诺'。
When writing a unit test in Jasmine, I get the following error when the $save call is executed: "Cannot read property '$promise' of undefined".
什么是测试在我的控制器,它包含上述code中的方法,最好的方法?
What's the best approach to testing the method in my controller which contains the above code?
如果您使用茉莉花的 spyOn()
函数来验证 $资源
方法被调用时,它会覆盖原来的 $资源
方法,一个实现了间谍的功能。
If you use Jasmine's spyOn()
function to verify that a $resource
method is called, it overwrites the original $resource
method with one that implements the "spying" functionality.
如果你的应用程序中的code依赖于 $资源
设置$承诺财产,或者它依赖返回的对象/数组从 $资源
,茉莉花的间谍功能,将不返回任何东西,或设置在$承诺属性的值。其结果是,被测试时,在你的应用程序完美的罚款code将失败。当你使用类似的事情发生 $ HTTP
与则()
,成功()
或错误()
功能。
If the code in your application relies on the $resource
setting the $promise property, or it relies on the returned object/array from the $resource
, the Jasmine's spy function won't return anything or set a value on the $promise property. As a result, perfectly fine code in your application will fail when being tested. A similar thing happens when you use $http
with the then()
, success()
, or error()
functions.
要解决,你可以使茉莉花的功能间谍以及通过做这样的事情调用原始的功能:
To work around that you can make Jasmine spy on the function as well as call the original function by doing something like this:
// Newer Jasmine 2.0 syntax:
spyOn(resource, "$save").and.callThrough();
// Older syntax:
spyOn(resource, "$save").andCallThrough();