测试以太坊事件日志与松露

时间:2016-04-14 15:34:46

标签: events logging mocha ethereum truffle

我有一个合约的功能,它会在每次通话时发出事件。

我想在每个测试中发出一个正在传递的事件,这里有一些测试:

var req = (from A in DatatableA
       join B in DatatableB 
        on A.Key1
            equals B.Key1  into DatatableResult
            select new
           {
                  Key1 = A.Key1    ,
                 Key2 = A.Key2    ,
               A= A.A ,
               x= B.x ,
               y= B.y ,

             }).ToList();

结果是:

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);
});

您可以看到记录的唯一一个失败。

有什么想法吗?

谢谢

6 个答案:

答案 0 :(得分:12)

您正在将tx哈希传递给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);
});

答案 1 :(得分:6)

从Truffle v3开始,您可以获得回调结果中的日志。所以你可以这样做:

insurance.send({from: accounts[0], value: web3.toWei(5, 'ether')}).then((result) => { assert.equal(result.logs[0].event, "Error", "Expected Error event") })

请参阅https://github.com/trufflesuite/truffle-contract#processing-transaction-results

答案 2 :(得分:5)

有一个帮手可以做到这一点:

npm install --save truffle-test-utils

在测试的顶部:

require('truffle-test-utils').init();

在你的测试中:

let result = await insurance.send({from: accounts[0], value: web3.toWei(5, 'ether')});
assert.web3Event(result, {
  event: 'Error',
  args: {
    error: 'Must send 10 ether'
  }
}, 'Error event when sending 5 ether');

完全披露:我是这个软件包的作者。我在SO上寻找这样的解决方案后写了它,但无法找到它。

答案 3 :(得分:2)

您也可以使用Truffle的测试工具expectEvent.js来代替自己编写代码:

const { inLogs } = require('openzeppelin-solidity/test/helpers/expectEvent')
require('chai').use(require('chai-bignumber')(BigNumber)).should()
...
{ logs: this.logs } = await this.token.burn(amount, { from: owner })
...
const event = inLogs(this.logs, 'Burn')
event.args.burner.should.eq(owner)
event.args.value.should.be.bignumber.equal(amount)

可以在松露的BurnableToken.behavior.js中找到一个例子。

答案 4 :(得分:0)

您可以使用truffle-assertions包,其中包含断言以检查是否已发出事件。它还可以选择传递过滤函数,以便检查事件参数的复杂条件。

npm install truffle-assertions

您可以将其导入测试文件的顶部:

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

在测试中使用它:

let txResult = await insurance.send({from: accounts[0], value: web3.toWei(5, 'ether')});
truffleAssert.eventEmitted(txResult, 'Error', (ev) => {
    return ev.error === 'Must send 10 ether';
}

免责声明:我创建了这个包以在我自己的测试中使用,并且通过添加过滤器功能,可以以非常简单的方式检查事件参数的复杂条件。我在我的博客上写了an article explaining this in more detail

答案 5 :(得分:0)

我能够找到一些参考资料来帮助解决这个问题,特别是如果您想使用async / await。

it('can create a unique star and get its name', async function () {
        const event = this.contract.starClaimed({});
        event.watch(async (err, result) => {
           if (err) console.log("Somethings wrong...");

           if (result.args.owner === accounts[0]) {
               let token = result.args._token;
               event.stopWatching;

               const star = await this.contract.tokenIdToStarInfo(token);

               assert.equal(star[0], 'awesome star!');
               assert.equal(star[1], 'yada yada yada');
               assert.equal(star[2], 'dec_test');
               assert.equal(star[3], 'mag_test');
               assert.equal(star[4], 'cent_test');
           }
        });

        await this.contract.createStar('awesome star!', 'yada yada yada', 'dec_test', 'mag_test', 'cent_test', {from: accounts[0]});
    });

这是我找到的参考:https://github.com/trufflesuite/truffle-contract/issues/117