Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 641
gaoban Avatar asked Mar 03 '14 07:03

gaoban


1 Answers

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

like image 115
glepretre Avatar answered Oct 10 '22 05:10

glepretre