如何在茉莉花中测试Ajax的已完成部分 [英] How to test done part of ajax in jasmine
问题描述
我非常喜欢此资源通常适用于AJAX,它可以测试AJAX参数中的success
或error
函数.
I really like this resource for AJAX in general and it works in terms of testing a success
or error
function that's within the AJAX parameters.
但是,当我选择不使用$.ajax({ ... success: ... })
并选择在外部使用.done()
时,我不确定如何进行测试.请帮助修改我的简单规格,谢谢!
However, when I instead choose to not have a $.ajax({ ... success: ... })
and choose to have a .done()
outside, I'm not sure how to test. Please help amend my simple spec, thanks!
代码
function itWorked() {}
function sendRequest(callbacks, configuration) {
$.ajax({}).done(function(response) {
itWorked()
});
}
规范
fdescribe("Ajax Tests", function() {
beforeEach(function() {
spyOn(window, "itWorked")
deferred = $.Deferred().done(function() { })
spyOn($, "ajax").and.callFake(deferred)
sendRequest()
})
it("should work", function() {
expect($.ajax).toHaveBeenCalled() // pass
expect(window.itWorked).toHaveBeenCalled(); // fail
});
});
推荐答案
好吧,问题所在的示例可能与您在本地运行的示例不同,但是它应该在spyOn($, "ajax").and.callFake(deferred)
行中失败,因为callFake
期望功能,而deferred
不是.相反,deferred
应该是已解决的承诺,并使用.and.returnValue
而不是.and.callFake
.
Well, probably the example in the question is not the same you are running local, but it should fail in the line spyOn($, "ajax").and.callFake(deferred)
because callFake
expect a function and deferred
is not. Instead, deferred
should be a resolved Promise and use .and.returnValue
instead of .and.callFake
.
这是一个可行的示例:
function itWorked() {
console.log("It worked!!");
}
function sendRequest(callbacks, configuration) {
$.ajax({}).done(function(response) {
itWorked();
});
}
describe("Ajax Tests", () => {
beforeEach(function() {
spyOn(window, "itWorked").and.callThrough();
deferred = $.Deferred().resolve(); // Call resolve
spyOn($, "ajax").and.returnValue(deferred); // Use return value
sendRequest();
});
it("should work", function() {
expect($.ajax).toHaveBeenCalled(); // pass
expect(window.itWorked).toHaveBeenCalled(); // pass
});
});
请注意,我已经添加了console.log("It worked!!");
并使用.and.callThrough();
只是在控制台中再次检查是否已记录有效!" .
Note that I've added console.log("It worked!!");
and use .and.callThrough();
just to double check in the console that "It worked!!" was logged.
调用 $ .Deferred().resolve()时,您可以传递模拟响应以在您的.done
或.then
回调中处理. .resolve({ success: true })
之类的东西. 在此处查看示例
When calling $.Deferred().resolve() you can pass a mocked response to deal with in your .done
or .then
callback. Something like .resolve({ success: true })
. Check an example here
希望有帮助
这篇关于如何在茉莉花中测试Ajax的已完成部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!