如何使用truffle来测试以太坊的事件日志Event logs?

如何使用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/

另外推荐一些之前的教程:

  • python以太坊,主要是针对python围绕web3.py进行区块链以太坊应用开发的讲解。
  • web3j,主要是针对java和android程序员围绕web3j库进行区块链以太坊开发的讲解。
  • php以太坊,主要是介绍使用php进行智能合约开发交互,进行账号创建、交易、转账、代币开发以及过滤器和事件等内容。
  • 以太坊开发,主要是介绍使用node.js、mongodb、区块链、ipfs实现去中心化电商DApp实战,适合进阶。
  • 以太坊教程,主要介绍智能合约与dapp应用开发,适合入门。

猜你喜欢

转载自blog.csdn.net/mongo_node/article/details/81076814