user2719805 user2719805 - 1 year ago 56
AngularJS Question

Jasmine How to test a function that returns an anonymous function

I have the following code in a service.

function getK(k) {
return function() {
return k;
};
}


I can test that getK was called with

beforeEach(inject(function(FiltersService){
this.service = FiltersService;
spyOn(this.service, 'getK');
}));

it("getK should be called", function(){
var key = "TEST";
var result = this.service.getK(key);
expect(this.service.getK).toHaveBeenCalled();
expect(this.service.getK).toHaveBeenCalledWith("TEST");
}


My question is how do I test the inner

return function() {
return k;
}


With Jasmine

EDIT

To try and further specify, the
getK function
is used to fill in an object as shown below. That object is part of a library that I am using that uses
key
. I guess I am a little confused on how to test this from a karma-jasmine perspective seeing that the actual implementation of
key
is part of a library that I do not control. So I am not sure how to write tests for the internal getK function or even for the below
valid
function to be sure the object is filled out properly

libObject.push({
Data: {
Name: 'test'
},
key: getK("TEST"),
valid: function() {
return true;
}
});

Answer Source

Unit testing supposes testing the code line by line for full coverage.

Considering that getK is exposed as FiltersService method, it is

expect(this.service.getK).toEqual(jasmine.any(Function));

var key = {};
var result = this.service.getK(key);

expect(result).toEqual(jasmine.any(Function));
expect(result()).toBe(key);

There's no need for a spy in this spec, because there's nothing to spy.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download