我通常的测试用例看起来像
it("should send get request", inject(function(someServices) {
//some test
}));
Run Code Online (Sandbox Code Playgroud)
并且Jasmine 2.0异步测试看起来应该是这样的
it("should send get request", function(done) {
someAsync.then(function(){
done();
});
});
Run Code Online (Sandbox Code Playgroud)
如何在一次测试中同时使用done和inject?
让我们看看我的代码:
$("#senderr").on("click", function(){
$.get("/echo/json").then(function(res){
//let's imagine something happen
throw "error";
});
});
$("#sendok").on("click", function(){
$.get("/echo/json").then(function(res){
$("#log").append("<li>send ok</li>");
});
});
$(document).on("ajaxStart", function(){
$("#log").append("<li>start</li>");
});
$(document).on("ajaxStop", function(){
$("#log").append("<li>stop</li>");
});
Run Code Online (Sandbox Code Playgroud)
如果按“发送确定”,您可以看到 ajaxStart 和 ajaxStop 事件已成功触发。但是,如果您只按一次“发送错误”按钮,该按钮会在 ajax 回调中引发运行时错误,则之前的“发送正常”行为将永远不会再次起作用 - ajaxStop 事件停止触发。
为什么 jQuery 这样做呢?除了到处使用 try-catch 之外,我还能做些什么来防止这种情况发生?