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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With