【问题标题】:How to mock jquery ajax calls, written in jquery.ready function using jasmine test如何模拟 jquery ajax 调用,使用 jasmine 测试用 jquery.ready 函数编写
【发布时间】:2014-12-10 05:28:45
【问题描述】:
我有一个场景,我在 jquery.ready 函数中调用 jquery ajax。所以一旦这个js被加载到页面中,ajax调用就会被提交。我正在为这个 js 编写 jasmine 测试用例。
问题是,当我在我的 specrunner.html 中包含这个 js 来编写 jasmine 测试时,jquery.ajax 被调用,因为它在 jquery.ready 中。我想模拟这个 ajax 调用。我已经尝试过使用 jasmine ajax,但没有帮助。
请帮忙。
【问题讨论】:
标签:
jquery
testing
jasmine
gui-testing
jasmine-jquery
【解决方案1】:
您想模拟 AJAX 调用还是响应?如果是后者,过去我用Sinon's fake server 模拟它。现在(Jasmine 2.X)拥有自己的fake XHR facility。一般来说,您将在 beforeEach 中包含以下内容:
beforeEach(function() {
jasmine.Ajax.install();
});
然后在您发送请求后,您将运行:
request = jasmine.Ajax.requests.mostRecent();
和
request.respondWith = {
status: 200,
responseText: '{"response":{"groups":["A","B","C"]]}}'
}