Mocha 测试未 运行 `try..finally` 子句

Mocha test not running the `try..finally` clause

我正在 运行使用 Mocha 进行 Node.js 测试。当我添加 try..finally 子句时,我希望 Mocha 在测试后会 运行 finally 位。它适用于错误和异常,但不适用于测试超时。

下面的测试详细说明了这个问题。

describe('try-finally', () => {
  it('should run finally with an error', async() => {
    console.log('starting')
    try {
      console.log('started')
      throw new Error('Error!')
      console.log('finished')
    } finally { 
      console.log('finally!')
    } 
  }); 
  it('should run finally with a timeout', async() => {
    console.log('starting')
    try {
      console.log('started')
      await timeout()
      console.log('finished')
    } finally {
      console.log('finally!')
    }
  });
});

function timeout() {
  return new Promise(ok => {
    setTimeout(ok, 10*1000)
  })
}

要 运行 测试:保存到文件 try-finally.js,使用 npm install -g mocha 安装 Mocha,然后 运行 使用 mocha --exit try-finally.js 进行测试。输出:

$ mocha --exit try-finally.js

  try-finally
starting
started
finally!
    1) should run finally with an error
starting
started
    2) should run finally with a timeout


  0 passing (2s)
  2 failing

  1) try-finally
       should run finally with an error:
     Error: Error!
      at Context.it (try-finally.js:9:13)

  2) try-finally
       should run finally with a timeout:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. /home/alex/devo/batrasio/try-finally.js)

两个测试都失败了;第一个 运行s finally 子句并显示 "finally!",而第二个超时(当测试默认超时为 2s 时等待 10s)并且不 运行 finally 子句。

在 Google 和此处的 Stack Overflow 上进行了几次搜索,但一无所获。我究竟做错了什么?这甚至可能吗,还是我需要使用令人讨厌的 beforeEach()afterEach() 函数?

finally 块将 运行 放在 try 块的内容之后,不一定是整个测试。错误和异常之类的东西本应在 try 块中捕获,但超时后,错误由 mocha 抛出(因此在 try 块之外)。

如果您需要在测试完成后 运行 finally 块并且花费的时间太长,您可以通过放置

来更改默认超时

this.timeout(<insert time in ms>);

在您的 it 函数内部(或者 describe 函数,如果您希望它应用于所有内容)。

如果您想在每次测试后都做同样的事情,那么是的,afterEach() 函数就是您的选择。