Mocha change timeout for afterEach

2020-04-08 13:46发布

问题:

I am writing a node application with mocha and chai. Some of the tests call an external API for integration tests, which might take up to 90sec to perform the action.

In order to cleanup properly, I defined an afterEach()-block, which will delete any generated remote resources, in case an expect fails and some resources weren't deleted.

The tests themselves have an increased timeout, while the rest of the tests should retain their default and small timeout:

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

However, I can't do the same with afterEach().timeout(120000), because the function does not exist - nor can I use the function ()-notation due to the unknown resource names:

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)
})

Any hints? Mocha is version 4.0.1, chai is 4.1.2

回答1:

The rules are same for all Mocha blocks.

timeout can be set for arrow functions in Mocha 1.x with:

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

And for 2.x and higher it, beforeEach, etc. blocks are expected to be regular functions in order to reach spec context. If suite context (describe this) should be reached, it can be assigned to another variable:

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 contexts are expected to be used like that, since spec context is useful, and there are virtually no good reasons to access suite context inside specs.

And done parameter or promise return are necessary for asynchronous blocks.



回答2:

If you need to use dynamic context you have to use normal function.

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