首页 > 解决方案 > 设置超时箭头函数

问题描述

我正在做一些 mocha 测试,我被要求重构我的代码,他们要求我使用箭头函数。

但现在我收到以下错误:

Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

这也发生在重构之前,但我使用了解决它:this.timeout(1000)但现在这不适用于箭头函数。如何设置高于 2000ms 的超时?下面是我的测试。

describe('Test', () => {
  token = 'un_assigned';
  before( (done) => {
    getToken('random_token', (response) => {
      token = response.token;
      fs.writeFileSync('./tests/e2e/helpers/token.json', JSON.stringify(response, null, 4));
      done();
    })
  });

  files.forEach(function (file) {
    it('Comparando file ' + file, (done) => {
      const id = file.split('./screenshots/')[1];
      compare(file, id, token, function (response) {
        expect(response.TestPassed).to.be.true;
        done();
      });
    });
  });
});

标签: node.jsmocha.js

解决方案


使用箭头函数时未绑定测试上下文。所以你不能使用this.timeout.

但是您可以通过这种方式在特定测试用例上设置超时:

it('Comparando file ' + file, (done) => {
  ...
}).timeout(1000);

推荐阅读