我没用过量角器。对于 Jasmine,我的理解是 done 使 Jasmine 等待但不是传统意义上的超时。它不像一个总是运行的计时器。我认为done 充当Jasmine 中的检查点。当Jasmine 看到一个规范使用done 时,它知道它不能继续下一步(比如运行下一个规范或将此规范标记为已完成,即声明当前规范的判断),除非代码段包含done已运行。
例如,jasmine 通过了这个规范,即使它应该失败,因为它没有等待 setTimeout 被调用。
fit('lets check done',()=>{
let i=0;
setTimeout(function(){
console.log("in timeout");
expect(i).toBeTruthy();//the spec should fail as i is 0 but Jasmine passes it!
},1000);
//jasmine reaches this point and see there is no expectation so it passes the spec. It doesn't wait for the async setTimeout code to run
});
但如果我的意图是让 Jasmine 等待 setTimeout 中的异步代码,那么我在异步代码中使用 done
fit('lets check done',(done)=>{
let i=0;
setTimeout(function(){
console.log("in timeout");
expect(i).toBeTruthy();//with done, the spec now correctly fails with reason Expected 0 to be truthy.
done();//this should make jasmine wait for this code leg to be called before declaring the verdict of this spec
},1000);
});
注意,done 应该在我要检查断言的地方调用。
fit('lets check done',(done)=>{
let i=0;
setTimeout(function(){
console.log("in timeout");
expect(i).toBeTruthy();//done not used at the right place, so spec will incorrectly ypass again!.
//done should have been called here as I am asserting in this code leg.
},1000);
done();//using done here is not right as this code leg will be hit inn normal execution of it.
});
总而言之,将 done 视为告诉 Jasmine - “我现在完成了”或“当此代码命中时我将完成”