Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub an AJAX call using Sinon

Tags:

jquery

ajax

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?

like image 882
Ubu Avatar asked Dec 19 '16 16:12

Ubu


1 Answers

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();
like image 121
niutech Avatar answered Oct 22 '22 04:10

niutech