1

I'm testing the ERC20 standard. I try to send a transaction from an account with balance=0, which should throw an error. I'm trying to catch it.

In my test function, I'm using the following:

contract('erc20 deployed', function(accounts) {
    it("should not transfer 1 token from address[0] to address[1]", function(done) {
        try{
            return erc20Instance.transfer(accounts[1], 1);
            should.fail("No error was thrown trying to cheat balance");
        }
        catch(error){
            done();
        }
    });
});

When I execute it with truffle test I get the following error:

  1) Contract: erc20 deployed
       should not transfer 1 token from address[0] to address[1]:
     Uncaught Error: VM Exception while processing transaction: revert

How can I catch it? My goal is to test the the transfer function, testing that address[0] can not effectively make the transaction.

4

Try this:

contract('erc20 deployed', function(accounts) {
    const REVERT = "VM Exception while processing transaction: revert";
    it("should not transfer 1 token from address[0] to address[1]", async function() {
        try {
            await erc20Instance.transfer(accounts[1], 1);
            throw null;
        }
        catch (error) {
            assert(error, "Expected an error but did not get one");
            assert(error.message.startsWith(REVERT), "Expected '" + REVERT + "' but got '" + error.message + "' instead");
        }
    });
});
2

As an alternative to goodvibration's answer, it's also possible to use my truffle-assertions library, which includes a helper function to assert that a contract function reverts.

It can be installed through npm

npm install truffle-assertions

Next, it can be imported at the top of your test file

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

Then it can be used inside your test:

contract('erc20 deployed', function(accounts) {
    it("should not transfer 1 token from address[0] to address[1]", async function() {
        await truffleAssert.reverts(erc20Instance.transfer(accounts[1], 1), null, "No error was thrown trying to cheat balance");
    });
});

The full documentation can be found on GitHub.

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.