大佬教程收集整理的这篇文章主要介绍了jquery – 使用Sinon.js并阻止对我的应用服务器的调用,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望我们sinon.js测试一段javascript以确保它在做两件事时调用$.ajax方法:
>我不想真正打到服务器
>我想模拟服务器的响应
所以这是JS:
$.ajax url: "/tickets/id.json" dataType: 'json' .done (data) => Handlebarstemplates["tickets/popup_title"] data
这是我的测试:
describe 'PopupDisplayer',-> beforeEach -> loadFixtures 'popup_displayer' new PopupDisplayer @title_stub = sinon.stub( Handlebarstemplates,"tickets/popup_title") @jquery_stub = sinon.stub(jQuery,'ajax').yieldsTo('done',{}) //This triggers the ajax call $('.popupable .title').mouseenter() afterEach -> Handlebarstemplates['tickets/popup_title'].restore() Handlebarstemplates['tickets/popup_content'].restore() jQuery.ajax.restore() @server.restore() it 'renders the title with the data returned from the server',-> expect(@title_stub).toHaveBeenCalledWith( {})
此测试失败但有以下异常:
TypeError: ajax expected to yield to 'done',but no object with such a property was passed. Received [[object Object]]
所以我想我想知道我是否可以模拟一个jQuery请求来获得一个可以成功响应.done调用的响应,显然我不太了解defferedObject().
... @jquery_stub = sinon.stub(jQuery,'ajax').returns done: (callBACk) -> callBACk {...} # your object here ...
请注意,这只会对完成的回调进行存根.如果你想测试其他行为,你可能需要实现其他处理程序(失败,然后等).
您还可以返回一个实际的jQuery Deferred对象:
... @deferred = new jQuery.Deferred @jquery_stub = sinon.stub(jQuery,'ajax').returns(deferred) ...
在这种情况下,您必须在进行测试之前显式触发返回的Deferred:
... @deferred.resolveWith(null,[{}]) # your object here ...
以上是大佬教程为你收集整理的jquery – 使用Sinon.js并阻止对我的应用服务器的调用全部内容,希望文章能够帮你解决jquery – 使用Sinon.js并阻止对我的应用服务器的调用所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。