mocha异步之done
发布于 10 年前 作者 353355756 8572 次浏览 最后一次编辑是 8 年前

今天看了一下mocha,前面的同步比较好理解,但是到异步的时候遇到了done,不太清楚,done方法做了什么,到网上都没找到特别好的例子。经过查找,看到了这篇文章 http://lostechies.com/derickbailey/2012/08/17/asynchronous-unit-tests-with-mocha-promises-and-winjs/ ,写的比较全。下面对done简单说明。 如下面的code:

var assert = require(“assert”); describe(“a test”, function(){ var foo = false; beforeEach(function(){ // simulate async call w/ setTimeout setTimeout(function(){ foo = true; }, 50); }); it(“should pass”, function(){ assert.equal(foo, true);
}); }); 开始,你可能会认为这个测试应该通过。当assert时认为“foo”变量被设置为true,因为在setTimeout中,它设置为true。但测试失败,因为assert运行在setTimeout的回调被调用之前。 现在done出场,这个“done”参数,在回调函数存在时,告诉mocha,你正在编写一个异步测试。这将导致mocha进入一个计时器,等待异步函数来完成 - 这时要么调用done()函数,或者超过2秒导致超时。 如下: var assert = require(“assert”); describe(“a test”, function(){ var foo = false; beforeEach(function(done){ setTimeout(function(){ foo = true; // complete the async beforeEach done(); }, 50); }); it(“should pass”, function(){ assert.equal(foo, true); }); }); 现在能测试通过了,至于两秒的问题,你把等待50,该为2000,哈哈。 还有一个问题是,在好多地方查到done方法是只有执行了done方法,下面的code才会执行下一步,但这个下一步不太清楚,在此说明: 继续看code:

describe(‘done’, function(){
it(‘done test’, function(done){
setTimeout(function(){ done(); }, 1900); }); it(“done test1”, function(){ console.log(“it里的输出”); }); console.log(“it外的输出”); }) ; 运行后,"it外的输出“先输出,证明,done只能控制后面的it里的方法。

回到顶部