很简单的问题:
我希望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()
的理解不够好。
发布于 2013-02-26 11:44:53
要模拟服务器的响应,需要对$.ajax
的返回值进行存根
...
@jquery_stub = sinon.stub(jQuery, 'ajax').returns
done: (callback) -> callback {...} # your object here
...
请注意,这仅是done
回调的存根。如果您想测试其他行为,您可能需要实现其他处理程序(fail
、then
等)。
还可以返回实际的jQuery延迟对象:
...
@deferred = new jQuery.Deferred
@jquery_stub = sinon.stub(jQuery, 'ajax').returns(deferred)
...
在这种情况下,您必须在执行测试之前显式地触发返回的延迟:
...
@deferred.resolveWith(null, [{}]) # your object here
...
https://stackoverflow.com/questions/10973839
复制相似问题