Lar*_*ars 5 javascript mocha.js node.js chai ecmascript-6
我正在用 mocha 和 chai 编写一个节点应用程序。一些测试调用外部 API 进行集成测试,这可能需要长达 90 秒才能执行操作。
为了正确清理,我定义了一个afterEach()-block,它将删除任何生成的远程资源,以防期望失败并且某些资源没有被删除。
测试本身有一个增加的超时,而其余的测试应该保留它们的默认和小超时:
it('should create remote resource', () => {...}).timeout(120000)
Run Code Online (Sandbox Code Playgroud)
但是,我不能对 做同样的事情afterEach().timeout(120000),因为该函数不存在 -function ()由于未知的资源名称,我也不能使用 -符号:
describe('Resources', function () {
beforeEach(() => {
this._resources = null
})
it('should create resources', async () => {
this._resources = await createResources()
expect(false).to.equal(true) // fail test, so...
await deleteResources() // will never be called
})
afterEach(async() => {
this._resources.map(entry => {
await // ... delete any created resources ...
})
}).timeout(120000)
})
Run Code Online (Sandbox Code Playgroud)
任何提示?mocha 是 4.0.1 版本,chai 是 4.1.2
所有 Mocha 块的规则都相同。
timeout 可以在 Mocha 1.x 中为箭头函数设置:
afterEach((done) => {
// ...
done();
}).timeout(120000);
Run Code Online (Sandbox Code Playgroud)
对于 2.x 和更高版本it,beforeEach, 等块应该是常规函数,以便达到规范上下文。如果describe this应达到套件上下文 ( ),则可以将其分配给另一个变量:
describe('...', function () {
const suite = this;
before(function () {
// common suite timeout that doesn't really need to be placed inside before block
suite.timeout(60000);
});
...
afterEach(function (done) {
this.timeout(120000);
// ...
done();
});
});
Run Code Online (Sandbox Code Playgroud)
Mocha 上下文应该像这样使用,因为规范上下文很有用,并且实际上没有充分的理由访问规范中的套件上下文。
和done参数或承诺回报是必要的异步块。