如何使用truffle来测试以太坊的事件日志Event logs?
例如我有一个智能合约函数,它在每次调用中触发事件。
我想在每次通过的测试中发送一个事件,下面是我的一些测试:
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); });
但是运行结果是:
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
Yo
可以看到以一个失败记录。
问题出在哪儿?
你的代码正在将 tx hash
哈希传递到done()
函数中。问题在这一行:
insurance.send({from: accounts[0], value: web3.toWei(5, 'ether')}).then(done).catch(done);
应该改成:
insurance.send({from: accounts[0], value: web3.toWei(5, 'ether')}).then(function() { done(); }).catch(done);
然后再去测试事件看看日志情况:
it("should check events", function(done) {
var watcher = contract.Reward();
// we'll send rewards
contract.sendReward(1, 10000, {from: accounts[0]}).then(function() {
return watcher.get();
}).then(function(events) {
// now we'll check that the events are correct
assert.equal(events.length, 1);
assert.equal(events[0].args.beneficiary.valueOf(), 1);
assert.equal(events[0].args.value.valueOf(), 10000);
}).then(done).catch(done);
});
原文《以太坊常见问题和错误》中的:
http://cw.hubwiz.com/card/c/ethereum-FAQ/1/1/7/
另外推荐一些之前的教程: