Last Updated: January 31, 2019
· dperrymorrow

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"});

3 Responses
Add your response

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 ·

thanks for pointing that out. fixed

over 1 year ago ·


over 1 year ago ·