javascript 使用 spy 进行单元测试失败。说间谍从未被召唤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22140869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:32:30  来源:igfitidea点击:

Unit test with spy is failing. Says spy was never called

javascriptangularjsunit-testingjasmine

提问by gaoban

This is the code I'm testing

这是我正在测试的代码

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

    };
}]);

And this is the Jasmine test for it

这是茉莉花测试

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

Why is this failing? It says

为什么这会失败?它说

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

“使用 [ { userName : 'Bob' } ] 调用了预期的 spy get 但从未调用过”。

.toHaveBeenCalled()also fails.

.toHaveBeenCalled()也失败了。

回答by glepretre

Shouldn't you set the spy before doing the GET request?

你不应该在做 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'});
}));

EDIT:The Arrange-Act-Assert pattern;)

编辑:安排-ACT-断言模式;)