Ubu
Ubu

Reputation: 51

How to stub an AJAX call using Sinon

I have a function that makes an AJAX request to an endpoint and gets back JSON. How can I fake that AJAX request using Sinon so that I can test that the function works properly?

Upvotes: 5

Views: 3666

Answers (1)

niutech
niutech

Reputation: 29962

If you are using jQuery.ajax(), you can stub it like this:

var returnData = {name: 'value'}
var stub = sinon.stub($, 'ajax');
stub.yieldsTo('success', returnData);

Then you write your test cases.

At the end, you should restore the original jQuery.ajax() function like this:

$.ajax.restore();

Upvotes: 7

Related Questions