Search code examples
jquerytestingjasminegui-testingjasmine-jquery

How to mock jquery ajax calls, written in jquery.ready function using jasmine test


I have a scenario where I am calling the jquery ajax inside jquery.ready function. So as soon as this js gets loaded in page, ajax call gets submited. I am writing jasmine test cases for this js. Problem is, when I include this js in my specrunner.html for writing jasmine test, jquery.ajax gets called, as it is inside jquery.ready. I want mock this ajax call. I already tried using jasmine ajax, but no help. Please help.


Solution

  • Do you want to mock the AJAX call, or the response? If it's the latter, In the past I used to mock it with Sinon's fake server. Now (Jasmine 2.X) has it's own fake XHR facility. In general you will have in the beforeEach something such as:

    beforeEach(function() {
      jasmine.Ajax.install();
    });
    

    Then after you send your request, you'd run:

    request = jasmine.Ajax.requests.mostRecent();
    

    and

    request.respondWith = {
          status: 200,
          responseText: '{"response":{"groups":["A","B","C"]]}}'
    }