0

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?

Wanderer
  • 544
  • 1
  • 7
  • 23

1 Answers1

1

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

Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20
  • This gives me an error getJasmineRequireObj is not defined. – Wanderer Sep 20 '17 at 16:24
  • You need to add the jasmine ajax plugin as a helper to your test framework - check out the link I supplied for more details. – Duncan Thacker Sep 20 '17 at 18:41
  • Call me thick.. I'm not sure what that means... I have installed it via npm. I `require('jasmine-core');` and `require('jasmine-ajax')`. I've tried `var jasmine = Object.assign({},require('jasmine-core'),require('jasmine-ajax'));` I've tried copying the mock-ajax.js file from node_modules to spec/helpers/ – Wanderer Sep 20 '17 at 19:36
  • I'm using jasmine 2.8.0 & jasmine-ajax 3.3.1 from npm. – Wanderer Sep 20 '17 at 19:37
  • Following [this](https://github.com/jasmine/jasmine-ajax/pull/124) pattern I created another helper that exposed getJasmineRequireObj() as a global and required my JSDOM domHelper.js. That seemed to get me past this error. – Wanderer Sep 20 '17 at 20:01