我可以以某种方式声明测试预计会有未处理的拒绝吗?

Can I somehow declare that a test expects to have unhandled rejections?

我有一个对某些代码施加“计量”的库。正常情况很容易测试,其中代码 运行s 完成并且不超过 meter。

我还想测试超出 meter 的情况,导致被测代码永远抛出,直到它展开给调用者。很容易测试代码只执行了我期望的部分。但是,在 promises 的情况下,超出的 meter 会像预期的那样在被测代码中导致一些未处理的拒绝。

AVA 目前未通过我的测试 运行,原因是:

  1 test passed
  1 unhandled rejection

实际上,测试减少到:

const expectedLog = ['a'];
test('unhandled rejection', async t => {
  const log = [];
  // I don't have control over the code in f():
  const f = async () => {
    log.push('a');
    // This is a side-effect, but fails the test.
    Promise.reject(RangeError('metering'));
    throw RangeError('metering');
  };
  await t.throwsAsync(() => f(), { instanceOf: RangeError });
  t.deepEqual(log, expectedLog);
});

有什么方法可以让我告诉 AVA 我预计会有 1 次未处理的拒绝?

我要求不要修改被测代码(上面的 f 函数),因为重点是测试无论不受信任的代码是什么,计量都会阻止代码停滞不前。

Is there any way for me to tell AVA that I expected the 1 unhandled rejection?

没有。未处理的拒绝表明存在错误,因此 AVA 将无法通过测试 运行。作为 AVA 的维护者,我认为没有足够的理由改变这种行为。

I require not to modify the code under test (the f function above), as the whole point is to test that metering stops the code dead in its tracks no matter what that untrusted code is.

拒绝承诺,然后垃圾收集,不会影响不受信任的代码。如果您在 async 函数中,您可以直接使用 throw