我非常喜欢AJAX的这一资源,它的工作原理是测试AJAX参数中的success
或error
函数。
但是,当我选择不使用$.ajax({ ... success: ... })
并选择在外部使用.done()
时,我不知道如何进行测试。请帮助修改我的简单规格,谢谢!
码
function itWorked() {}
function sendRequest(callbacks, configuration) {
$.ajax({}).done(function(response) {
itWorked()
});
}
Spec
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
});
});
发布于 2018-12-03 15:37:22
嗯,问题中的例子可能与运行本地的不同,但是它应该在行spyOn($, "ajax").and.callFake(deferred)
中失败,因为callFake
期望一个函数,而deferred
不是。相反,deferred
应该是一个明确的承诺,使用.and.returnValue
而不是.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();
,只需在控制台中重复检查“它成功了!”被记录下来了。
当调用$.Deferred().resolve()时,可以在.done
或.then
回调中传递一个模拟的响应来处理。有点像.resolve({ success: true })
。检查这里的一个例子
希望它能帮上忙
https://stackoverflow.com/questions/53568192
复制相似问题