Search code examples
angularjsunit-testingkarma-jasminespy

is it possible to test the contents of a function that is the parameter of a spy


I'm testing a directive in angular and for code coverage purposes i need to get into that function which is passed to the second parameter of the remove function:

Myservice.remove(param1, function() {
   //test contents of this..
});

however Myservice is mocked, with the remove function being a spy:

myservice = {
    remove: jasmine.createSpy('Myservice.remove')
}

I've tried callThrough() and callFake() but i believe these are more to just return the result of remove, not cover the parameter function, so naturally i get no difference.

so in my test i have the following:

it('should do something', function() {
    // generic directive setup
    expect(myservice.remove).toHaveBeenCalled();
});

this works and the tests passes, however i'm unable to cover that function in the param, any ideas how to proceed?


Solution

  • the answer was to call a fake function with the correct params in and then calling the function within it.

    myservice = {
        remove: jasmine.createSpy('Myservice.remove').and.callFake(function(data, callback) {
            callback();
        });
    }
    

    the same test passes, but now the coverage fully covers the function passed in as the param.