I have a contract's function which emit events on each call.
I would like to have an event emitted on each test which are passing, here are some tests :
it("should emit Error event when sending 5 ether", function(done){
var insurance = CarInsurance.deployed();
insurance.send({from: accounts[0], value: web3.toWei(5, 'ether')}).then(done).catch(done);
});
it("should emit Error event when sending 5 ether", function(done){
var insurance = CarInsurance.deployed();
insurance.send({from: accounts[0], value: web3.toWei(5, 'ether')}).then(function(txHash){
assert.notEqual(txHash, null);
}).then(done).catch(done);
});
it("should emit Error event when sending 5 ether", function(done){
var insurance = CarInsurance.deployed();
insurance.send({from: accounts[0], value: web3.toWei(5, 'ether')}).then(function(done){
done();
}).catch(done);
});
The results are :
1) should emit Error event when sending 5 ether
Events emitted during test:
---------------------------
Error(error: Must send 10 ether)
---------------------------
✓ should emit Error event when sending 5 ether (11120ms)
✓ should emit Error event when sending 5 ether (16077ms)
3 passing (51s)
1 failing
1) Contract: CarInsurance should emit Error event when sending 5 ether:
Error: done() invoked with non-Error: 0x87ae32b8d9f8f09dbb5d7b36267370f19d2bda90d3cf7608629cd5ec17658e9b
You can see that the only one which is logged fail.
Any idea ?
Thank you
You can use the
truffle-assertions
package, which has an assertion to check that an event has been emitted. It also has the option to pass a filter function in order to check complex conditions to the event arguments.You can import it at the top of your test file:
And use it inside your test:
Disclaimer: I created this package to use in my own tests, and by adding the filter function, it is possible to check complex conditions to the event arguments, in a very straightforward way. I wrote an article explaining this in more detail on my blog.
Since Truffle v3 you get the logs in the callback result. So you could do something like:
insurance.send({from: accounts[0], value: web3.toWei(5, 'ether')}).then((result) => { assert.equal(result.logs[0].event, "Error", "Expected Error event") })
See https://github.com/trufflesuite/truffle-contract#processing-transaction-results
I was able to track down some references to help with this, especially if you want to use async/await.
Here's the reference I found: https://github.com/trufflesuite/truffle-contract/issues/117
You are passing tx hash into done() function. I think the problem is in line:
Change it to:
To test for events:
Instead of writing your own, you can also use Truffle's test utils expectEvent.js:
An example can be found in Truffle's BurnableToken.behavior.js.
There is a helper to do just this:
At the top of your test:
In your test:
Full disclosure: I'm the author of this package. I wrote it after looking for such solution on SO, but couldn't find it.