这是我测试的代码
eventsApp.factory('userData', ['userResource', function(userResource){
return{
getUser: function(userName, callback){
return userResource.get({userName:userName}, function(user){
if(callback)
callback(user);
});
};
}]);
这是茉莉花的测试
describe('userData', function(){
var mockUserResource;
beforeEach(module('eventsApp'));
beforeEach(function(){
mockUserResource = {get: function(){} };
module(function($provide){
$provide.value('userResource', mockUserResource);
});
});
it('should make a call to userResource.get with provided userName', inject(function(userData){
userData.getUser('Bob');
spyOn(mockUserResource, 'get');
expect(mockUserResource.get).toHaveBeenCalledWith({userName:'Bob'});
}));
});
为什么会失败?它说
"预期的间谍来自[{userName:' Bob' }] 但它从未被称为"。
.toHaveBeenCalled()
也失败了。
答案 0 :(得分:14)
在执行GET请求之前,您不应该设置间谍吗?
it('should make a call to userResource.get with provided userName', inject(function(userData){
//arrange
spyOn(mockUserResource, 'get');
//act
userData.getUser('Bob');
//assert
expect(mockUserResource.get).toHaveBeenCalledWith({userName:'Bob'});
}));