2017-09-14 103 views
3

我有以下的测试案例:与摩卡做()和异步等待悖论问题

it("should pass the test", async function (done) { 
     await asyncFunction(); 
     true.should.eq(true); 
     done(); 
    }); 

运行它断言:

Error: Resolution method is overspecified. Specify a callback or return a Promise; not both.

如果我删除done();声明,它断言:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

如何解决这个悖论?

+2

当你删除'done();',你是否也删除了'd函数中的一个参数? –

+0

不应该有返回声明吗?我在印象之下所有的同步功能需要返回解决。 –

+0

@ShyamBabu:不,如果没有明确的'return',他们等待的最后一个承诺完成后,他们用'undefined'解决。 –

回答

4

您还需要删除done参数,而不仅仅是调用它。像Mocha这样的测试框架可以查看函数的参数列表(或者至少它的参数)来知道您是使用done还是类似的。

采用摩卡3.5.3,这对我的作品(不得不改变true.should.be(true)assert.ok(true)因为前者抛出错误):

const assert = require('assert'); 

function asyncFunction() { 
    return new Promise(resolve => { 
     setTimeout(resolve, 10); 
    }); 
} 

describe('Container', function() { 
    describe('Foo', function() { 
    it("should pass the test", async function() { 
     await asyncFunction(); 
     assert.ok(true); 
    }); 
    }); 
}); 

但是,如果我添加done

describe('Container', function() { 
    describe('Foo', function() { 
    it("should pass the test", async function (done) { // <==== Here 
     await asyncFunction(); 
     assert.ok(true); 
    }); 
    }); 
}); 

。 ..然后我得到

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.