如何使用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/另外推薦一些之前的教程: