4

How does one test a transaction that is supposed to fail when testing with truffle?

For example, say I was testing an ERC token, in which accounts[0] had a balance of 20. Within a test, I call ERC.transfer(accounts[1], 25, {from: accounts[0]}), hoping to make sure that this would fail. How would I confirm that it did fail?

Sure, I could check that the balances of accounts[0] and accounts[1] do not change - but it seems like there may be a more elegant way to do so. Is there a way to do this?

1

Maybe this gist can help you

export default async promise => {
  try {
    await promise;
  } catch (error) {
    // TODO: Check jump destination to destinguish between a throw
    //       and an actual invalid jump.
    const invalidJump = error.message.search('invalid JUMP') >= 0;
    // TODO: When we contract A calls contract B, and B throws, instead
    //       of an 'invalid jump', we get an 'out of gas' error. How do
    //       we distinguish this from an actual out of gas event? (The
    //       testrpc log actually show an 'invalid jump' event.)
    const outOfGas = error.message.search('out of gas') >= 0;
    assert(
      invalidJump || outOfGas,
      "Expected throw, got '" + error + "' instead",
    );
    return;
  }
  assert.fail('Expected throw not received');
};
0

You can use my truffle-assertions library to test for reverts or other failures.

It can be installed with npm:

npm install truffle-assertions

And then imported at the top of your file:

const truffleAssert = require('truffle-assertions');

You can then use it inside your tests like this:

// when you want to test revert
truffleAssert.reverts(ERC.transfer(accounts[1], 25, {from: accounts[0]}));

// or general failure
truffleAssert.fails(ERC.transfer(accounts[1], 25, {from: accounts[0]}));

The full method documentation can be found on the GitHub repository.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.