I've got a JS method in my node.js app that I want to unit test. It makes several calls to a service method, each time passing that service a callback; the callback accumulates the results.
How can I use Jasmine to stub out the service method so that each time the stub is called, it calls the callback with a response determined by the arguments?
This is (like) the method I'm testing:
function methodUnderTest() {
var result = [];
var f = function(response) {result.push(response)};
service_method(arg1, arg2, f);
service_method(other1, other2, f);
// Do something with the results...
}
I want to specify that when service_method is called with arg1 and arg2, the stub will invoke the f callback with a particular response, and when it is called with other1 and other2, it will invoke that same callback with a different particular response.
I'd consider a different framework, too. (I tried Nodeunit, but didn't get it to do what I wanted.)
You should be able to use the callFake
spy strategy. In jasmine 2.0 this would look like:
describe('methodUnderTest', function () {
it("collects results from service_method", function() {
window.service_method = jasmine.createSpy('service_method').and.callFake(function(argument1, argument2, callback) {
callback([argument1, argument2]);
});
arg1 = 1, arg2 = 'hi', other1 = 2, other2 = 'bye';
expect(methodUnderTest()).toEqual([[1, 'hi'], [2, 'bye']]);
});
});
Where methodUnderTest
returns the results array.