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

倖福魔咒の 提交于 2019-12-10 07:40:49

问题


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".

.toHaveBeenCalled() also fails.


回答1:


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

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



来源:https://stackoverflow.com/questions/22140869/unit-test-with-spy-is-failing-says-spy-was-never-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!