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?

5 Answers 5

const ERROR_MSG = 'VM Exception while processing transaction: revert';
ContractName = await ContractName.new();
it('should never be zero', async() => {
   await ContractName

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


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)

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));

Complement to Rosco Kalis' post: Has worked fine for me ;-)

But you have do it exactly like he wrote. For the normal asserts the await is within the brackets.

For example:

assert.equal(await instance.calculate(2), 2));

For checking the revert the await is at the beginning of the line. It does not work with the await within the brackets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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