csjoshi04
csjoshi04

Reputation: 51

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.

Upvotes: 1

Views: 505

Answers (1)

Gabriel Kohen
Gabriel Kohen

Reputation: 4296

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"]]}}'
}

Upvotes: 1

Related Questions