足够简单的问题:
我希望我们 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()
足够好。
要模拟服务器的响应,您需要存根以下返回值$.ajax
:
...
@jquery_stub = sinon.stub(jQuery, 'ajax').returns
done: (callback) -> callback {...} # your object here
...
请注意,这只会存根done
打回来。如果您想测试其他行为,您可能需要实现其他处理程序(fail
, then
etc.).
您还可以返回一个实际的 jQuery Deferred 对象:
...
@deferred = new jQuery.Deferred
@jquery_stub = sinon.stub(jQuery, 'ajax').returns(deferred)
...
在这种情况下,您必须在进行测试之前显式触发返回的 Deferred:
...
@deferred.resolveWith(null, [{}]) # your object here
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)