gpt4 book ai didi

javascript - spy 单元测试失败。说 spy 从未被称为

转载 作者:搜寻专家 更新时间:2023-11-01 04:50:25 28 4
gpt4 key购买 nike

这是我正在测试的代码

eventsApp.factory('userData', ['userResource', function(userResource){
return{
getUser: function(userName, callback){
return userResource.get({userName:userName}, function(user){
if(callback)
callback(user);
});

};
}]);

这是 Jasmine 测试

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'});
}));
});

为什么会失败?它说

"Expected spy get to have been called with [ { userName : 'Bob' } ] but it was never called".

.toHaveBeenCalled() 也失败了。

最佳答案

难道不应该在执行 GET 请求之前设置 spy 吗?

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'});
}));

编辑 Arrange-Act-Assert pattern ;)

关于javascript - spy 单元测试失败。说 spy 从未被称为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22140869/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com