solidity – How to Check Events in Truffle Tests

eventssoliditytestingtruffle

What's the best way to check that events were fired in a Truffle test?

Best Answer

I wrote the truffle-assertions package just for this. It has an assertion to check that an event has been emitted. Essentially, it is similar to the older answer here, but it does not need to check a specific index of the logs, and it has the option add complex conditions in a straightforward way by passing a filter function.

npm install truffle-assertions

You can import it at the top of your test file:

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

And use it inside your test:

truffleAssert.eventEmitted(result, 'TestEvent', (ev) => {
    return ev.param1 === 10 && ev.param2 === ev.param3;
});

I wrote a blog post that goes over the functionality with a detailed use case for further reading: Checking events when testing Solidity smart contracts with Truffle