我正在进行单元测试,目前正在探索Mocha,Chai,Sinon设置,并在浏览器中进行测试。
我有一个javascript块,可以像这样对服务器进行ajax调用
PromptBase.prototype.fetchAndSetTemplateString = function() {
var deferred = $.Deferred();
$.ajax({
url: "/someurl",
type: "GET"
})
.done(function(response) {
if (response.status.toLowerCase() === "success") {
deferred.resolve(response.templateString);
}
});
return deferred.promise();
};
PromptBase.prototype.fetchPromptTemplate = function() {
var promise = this.fetchAndSetTemplateString();
$.when(promise).done(function(promptHtml) {
//set the templateString to promptHtml here
});
};
//Register a custom event on document to fire ajax request.
$(document).on("customevent", function(event) {
promptInstance.fetchPromptTemplate(promptParams.fetchTemplateOnEvent);
});
现在我有一个使用fakeServer
的测试用例describe("TemplateFetch", function() {
before(function() {
this.server = sinon.fakeServer.create(); // and other setup
});
after(function() {
this.server.restore(); // and other clean up
});
it("should fetch template string from server, when fetchTemplateEvent is fired", function() {
var expectedTemplateString = "templateStringFromServer";
var templateAjaxUrl = '/someurl';
//faking a server response
this.server.respondWith("GET", templateAjaxUrl,
[200, {"Content-Type": "application/json"},
'{"status": "success", "templateString": "'+ expectedTemplateString +'"}']);
// Now trigger even that fetches the template
$(document).trigger("customevent");
// This calls the ajax done function, which resolves the promise
this.server.respond();
//debugger shows that templateString is set here
expect(this.instance.templateString).to.eqaul("something");
});
});
但是我的测试输出超时错误
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
因此fakeServer.respond()
调用确保调用ajax->done
函数,从而导致承诺被解析。当我调试时,我可以看到expect
测试应该匹配两个字符串。我该如何解决这里的超时问题?我也试过添加完成回调但无济于事。
任何输入都表示赞赏。谢谢你的阅读。