1

If I write a function like so:

function calculate(int x) public returns (int) {
    require(x > 0);
    // Do other stuff
    return x;
}

How would I write a JavaScript unit test in Truffle verifying that the require fails when I try to call the function with a parameter of -1?

Obviously, this is just an illustrative example. I can't seem to find any documentation online.

it("should never be zero", function () {
    return ContractName.deployed().then(function(instance) {
        return instance.calculate.call(0);
    }).then(function (result) {
        // What do I put here?
    });
})
3
require('chai')
 .use(require('chai-as-promised'))
 .should();
const ERROR_MSG = 'VM Exception while processing transaction: revert';
ContractName = await ContractName.new();
it('should never be zero', async() => {
   await ContractName
   .calculate(-1)
   .should.be.rejectedWith(ERROR_MSG);
})
3

Do you use TestRPC or Geth for your tests? They can behave different and for my unit testing where it should fail, I follow this instruction:

When TestRPC and Geth throw, they behave in a different manner. This Gist is an example on how to cover such a situation. https://gist.github.com/xavierlepretre/d5583222fde52ddfbc58b7cfa0d2d0a9

2

You can do something like this:

it('should never be zero', async () => {
    const instance = await ContractName.deployed()
    let err = null

    try {
      await instance.calculate.call(-1)
    } catch (error) {
      err = error
    }

    assert.ok(err instanceof Error)
})
1

The answers that do an inline try catch make for quite a bit of boilerplate. This is exactly why I added revert and other failure testing as a feature to my truffle-assertions library. This allows you to assert reverts and other failures in a straightforward way. It also includes support for the new Truffle v5 functionality that finally enables us to retrieve the revert reason string.

The library can be installed through npm and imported at the top of the test javascript file:

npm install truffle-assertions

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

After which it can be used inside the tests:

await truffleAssert.reverts(instance.calculate(-1));

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.