gaoban
gaoban

Reputation: 95

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

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.

Upvotes: 6

Views: 20579

Answers (1)

glepretre
glepretre

Reputation: 8167

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

Upvotes: 18

Related Questions