我正在使用 mocha 和 chai 编写 Node 应用程序。一些测试调用外部 API 进行集成测试,这可能需要长达 90 秒的时间来执行操作。
为了正确清理,我定义了一个 afterEach()
block ,它将删除任何生成的远程资源,以防 expect 失败并且某些资源未被删除。
测试本身有一个增加的超时,而其余的测试应该保留他们的默认和小超时:
it('should create remote resource', () => {...}).timeout(120000)
但是,我不能对 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)
})
有什么提示吗? Mocha是4.0.1版本,chai是4.1.2
最佳答案
所有 Mocha block 的规则都是相同的。
timeout
可以为 Mocha 1.x 中的箭头函数设置:
afterEach((done) => {
// ...
done();
}).timeout(120000);
对于 2.x 和更高版本的 it
、beforeEach
等,为了达到规范上下文, block 应该是常规函数。如果套件上下文(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();
});
});
Mocha 上下文应该像那样使用,因为规范上下文很有用,而且几乎没有充分的理由在规范中访问套件上下文。
done
参数或 promise 返回对于异步 block 是必需的。
关于javascript - afterEach 的 Mocha 更改超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47281828/