为什么我的 sinon 测试超时而不是失败?

Why is my sinon test timing out instead of failing?

下面是被测代码:

function timeout(): Promise<NodeJS.Timeout> {
  return new Promise(resolve => setTimeout(resolve, 0));
}

async function router(publish: Publish): Promise<void> => {
  await timeout();
  publish('requestObject');
};

这是我的测试。如果我使用下面的 try/catch,它会立即失败并显示正确的错误。

it.only('returns a valid response', (done) => {
    const publish = sinon.stub();

    publish.callsFake((publishResponse) => {
      try {
        expect(publishResponse).to.equal('wrong');
        done();
      } catch (error) {
        done(error);
      }
    });

    router(publish);

    sinon.restore();
});

如果我删除 try/catch 测试超时:

publish.callsFake((publishResponse) => {
  expect(publishResponse).to.equal('wrong');
  done();
});

Error: Timeout of 5000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

我猜 promise 没有解决是因为 expect 失败了。所以它没有达到 done()。有没有办法让我更干净地重写它?或者使用 try/catch 是编写此测试的合适方法吗?

我阅读 时遇到了类似的问题,他们说要确保被测代码不会吞噬错误。但是在我的代码中,我没有看到任何代码吞下错误。

我通过等待被测代码而不是使用 callback/done 结构来简化它,并使用参数期望 (calledWith) 而不是在假回调中执行期望。

我不太确定为什么用这个代替回调方法。

  it.only('returns a valid response', async () => {
    const publish = sinon.stub();

    await router(publish);
    expect(publish).to.be.calledWith('wrong');

    sinon.restore();
  });