当使用Jasmine在JS中测试AJAX调用时,.andReturn(..)和.respondWith(
When testing AJAX calls in JS with Jasmine, what is the difference between .andReturn(...) and .respondWith(...)?
使用jasmine ajax库测试JavaScript代码时,我可以模拟ajax响应。特别是,我可以定义将给予特定ajax请求的响应。似乎(至少)有两种不同的方法:
方法#1:
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
contentType: 'text/plain',
responseText: 'my response'
});
方法#2:
jasmine.Ajax.stubRequest('my/url').andReturn({
'responseText': 'my response'
});
如果我的mostRecent
请求是指向url my/url
,那么这两者之间还有什么区别?
M.E.Trostler在"JavaScript单元测试"系列视频中向我介绍了这两种方法,但在这些视频中,在StackOverflow的搜索中,或在Jasmine的ajax.js插件在线文档中,我都找不到明确的答案。
在我自己深入研究之后,我相信这两个命令之间的区别至少部分在于模拟ajax调用的响应时间。简而言之:
- CCD_ 3现在发送对过去未应答的ajax调用的响应
andReturn
建立一个响应,以便在将来发送ajax调用时立即发送
在下面的两个示例中,验证onreadystatechange
处理程序中的回调可以显示是否返回了对ajax调用的响应,因为这样的响应将触发回调。在方法#1中,ajax调用被发送,但在调用respondWith
之前保持未应答状态。在方法#2中,响应是预先设置的,这样一旦发送ajax调用,就会返回一个响应。
方法#1:
setUpAndSendAjaxCall1();
expect(onreadystatechangeCallback1).not.toHaveBeenCalled();
jasmine.Ajax.requests.mostRecent().respondWith({
...
"responseText": "response #1"
});
expect(onreadystatechangeCallback1).toHaveBeenCalledWith("response #1");
方法#2:
jasmine.Ajax.stubRequest(myUrl).andReturn({
...
"responseTest": "response #2"
});
setUpAndSendAjaxCall2();
expect(onreadystatechangeCallback2).toHaveBeenCalledWith("response #2");