断言不会捕获错误

Assert doesn't catch errors

我有这个功能:

await sendTx(newProxyAddr, false, 'initialize', [0, nullAddr]);

...产生此错误:

Error: VM Exception while processing transaction: reverted with reason string 'Initializable: contract is already initialized'

但是当我尝试使用以下方法捕获测试错误时:

assert.throws(async () => {
   await sendTx(newProxyAddr, false, 'initialize', [0, nullAddr]);
}, Error, 'Thrown');

...,它告诉我:

AssertionError: expected [Function] to throw an error

我是不是漏掉了什么?

谢谢!

您应该使用 Node.js assert.rejects(asyncFn[, error][, message]) API 作为异步函数或 JS promise。

assert.throws 调用 getActual(promiseFn) 函数,该函数不会 await promiseFn,参见 v14.19.3/lib/assert.js#L899

assert.rejects 调用 await waitForActual(promiseFn) 将等待 promiseFn,参见 v14.19.3/lib/assert.js#L909

例如

const assert = require('assert');

async function sendTx() {
  throw new Error('error happens');
}

(async () => {
  await assert.rejects(
    async () => {
      await sendTx();
    },
    {
      name: 'Error',
      message: 'error happens',
    },
  );
})();