如何使用Sinon存根AJAX调用 [英] How to I stub an AJAX call using Sinon

查看:79
本文介绍了如何使用Sinon存根AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数向端点发出AJAX请求并返回JSON,如何使用Sinon伪造AJAX请求以便我可以测试该函数是否正常工作?

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

推荐答案

如果你使用的是 jQuery.ajax(),你可以像这样存根:

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

然后编写测试用例。

最后,你应该恢复原来的 jQuery.ajax()函数,如下所示:

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

$.ajax.restore();

这篇关于如何使用Sinon存根AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆