ogjloq
Last Updated: February 25, 2016
·
10.38K
· dperrymorrow
37b092a324da25d53fd63d780692b174

Stubbing Out $.ajax in Jasmine and calling through

So your'e testing your Javascript with Jasmine, but you dont want you ajax calls to fire. But you do want to test the functionality of handling the response of the ajax requests. Here's how.

You can use Jasmine's spyOn function to accomplish this.

spyOn( $, 'ajax' ).andCallFake( function (params) {

  params.success({foo: 'bar'});
  
});

This will keep $.ajax from firing but will trigger your success callback function with the object foo: 'bar'

There you go. Now you can test your ajax success response handers without needing remote endpoints in your test suite.

You can also do the same for testing error handling in your code

spyOn( $, "ajax" ).andCallFake( function (params) {
    
  params.error({foo: "bar"});
  
});
Say Thanks
Respond

2 Responses
Add your response

7873

Thanks, this may help on my problem. I think you left out a curly brace after 'bar' in the first code block.

over 1 year ago ·
7875
37b092a324da25d53fd63d780692b174

thanks for pointing that out. fixed

over 1 year ago ·