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"});
});
Written by David Morrow
Related protips
3 Responses
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
·
Thanks
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#