摩卡更改afterEach的超时

时间:2017-11-14 09:18:58

标签: javascript node.js ecmascript-6 mocha chai

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

为了正确清理,我定义了一个afterEach() - 块,它将删除任何生成的远程资源,以防止期望失败且某些资源未被删除。

测试本身具有增加的超时,而其余测试应保留其默认和小超时:

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

2 个答案:

答案 0 :(得分:3)

所有Mocha块的规则都相同。

可以在Mocha 1.x中为箭头函数设置

timeout

  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参数或promise返回。

答案 1 :(得分:2)

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

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