Home > front end >  Assert doesn't catch errors
Assert doesn't catch errors

Time:05-30

I have this function:

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

...that produces this error:

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

But when I try to catch the error on a test using:

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

..., it tells me:

AssertionError: expected [Function] to throw an error

Am I missing something?

Thanks!

CodePudding user response:

You should use Node.js assert.rejects(asyncFn[, error][, message]) API for async function or JS promise.

assert.throws calls getActual(promiseFn) function which will NOT await the promiseFn, see v14.19.3/lib/assert.js#L899

assert.rejects calls await waitForActual(promiseFn) will await the promiseFn, see v14.19.3/lib/assert.js#L909

E.g.

const assert = require('assert');

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

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