Reputation: 590
I have module that contains a load function and that load function calls jQuery's getJSON function
load(key,callback){
// validate inputs
$.getJSON( this.data[key],'',function(d){
switch(key){
// do some stuff with the data based on the key
}
callback('success');
});
}
With Jasmine 2.0 How can I mock out the call to getJSON but supply the data to the anonymous function?
Upvotes: 0
Views: 701
Reputation: 5188
I recommend using Jasmine's ajax plugin, which mocks out all AJAX calls (getJSON is an ajax call). Here's a sample of how to do it:
//initialise the ajax mock before each test
beforeEach( function() { jasmine.Ajax.install(); });
//remove the mock after each test, in case other tests need real ajax
afterEach( function() { jasmine.Ajax.uninstall(); });
describe("my loader", function() {
it("loads a thing", function() {
var spyCallback = jasmine.createSpy();
doTheLoad( "some-key", spyCallback ); //your actual function
//get the request object that just got sent
var mostRecentRequest = jasmine.Ajax.requests.mostRecent();
//check it went to the right place
expect( mostRecentRequest.url ).toEqual( "http://some.server.domain/path");
//fake a "success" response
mostRecentRequest.respondWith({
status: 200,
responseText: JSON.stringify( JSON_MOCK_RESPONSE_OBJECT );
});
//now our fake callback function should get called:
expect( spyCallback ).toHaveBeenCalledWith("success");
});
});
There's other approaches, but this one has worked really well for me. More documentation here:
https://github.com/jasmine/jasmine-ajax
Upvotes: 1