afterEach 的 Mocha 更改超时

Mocha change timeout for afterEach

我正在用 mocha 和 chai 编写一个节点应用程序。一些测试调用外部 API 进行集成测试,执行该操作可能需要长达 90 秒。

为了正确清理,我定义了一个 afterEach()-block,它将删除任何生成的远程资源,以防 expect 失败并且一些资源没有被删除。

测试本身有一个增加的超时,而其余的测试应该保留他们的默认和小超时:

it('should create remote resource', () => {...}).timeout(120000)

但是,我不能对 afterEach().timeout(120000) 做同样的事情,因为该函数不存在 - 由于资源名称未知,我也不能使用 function ()-notation:

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

如果您需要使用动态上下文,则必须使用普通函数。

describe('Resources', function () {
  // ...
  afterEach(function (){
    this.timeout(120000)  // this should work
    // ... delete any created resources ...
  })
})

所有 Mocha 块的规则都相同。

timeout 可以为 Mocha 1.x 中的箭头函数设置:

  afterEach((done) => {
    // ...
    done();
  }).timeout(120000);

并且对于 2.x 和更高的 itbeforeEach 等,为了达到规范上下文,块应该是常规函数。如果套件上下文(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 参数或承诺 return 是异步块所必需的。