代码之家  ›  专栏  ›  技术社区  ›  mareoraft

如何在javascript/truffle中为每个测试创建新的以太坊/实体契约

  •  1
  • mareoraft  · 技术社区  · 7 年前

    背景

    我已经写了一个以太坊智能合约 Solidity Ganache 并使用 truffle migrate .

    要求

    我想用JavaScript测试我的合同。我想创建一个 每个测试的合同实例。

    我试过的

    我创建了一个测试文件 tests/test.js 在我的项目中:

    const expect = require('chai').expect
    
    const Round = artifacts.require('Round')
    
    
    contract('pledgersLength1', async function(accounts) {
        it('1 pledger', async function() {
            let r = await Round.deployed()
            await r.pledge(5)
            let len = (await r.pledgersLength()).toNumber()
            expect(len).to.equal(1)
        })
    })
    contract('pledgersLength2', async function(accounts) {
        it('2 pledgers', async function() {
            let r = await Round.deployed()
            await r.pledge(5)
            await r.pledge(6)
            let len = (await r.pledgersLength()).toNumber()
            expect(len).to.equal(2)
        })
    })
    

    我和你一起跑 truffle test . 基本上是 Mocha ,但是 truffle 定义 artifacts

    松露 contract 功能 is almost the same describe 合同 每次都会让我的合同变新。没有。也许我可以用 new Round() 而不是 Round.deployed() 但我不知道怎么做。

    用松露。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Zulhilmi Zainudin    7 年前

    .new .deployed 都不一样。看看我发现了什么 here .

    按照这个例子,它应该可以解决您的问题:

    // Path of this file: ./test/SimpleStorage.js
    var simpleStorage = artifacts.require("./SimpleStorage.sol");
    
    contract('SimpleStorage', function(accounts) {
    
      var contract_instance;
    
      before(async function() {
        contract_instance = await simpleStorage.new();
      });
    
      it("owner is the first account", async function(){
        var owner = await contract_instance.owner.call();
        expect(owner).to.equal(accounts[0]);
      });
    
    });
    

    这个 .新的

    .已部署 truffle migrate 命令。

    所以你总是从新合同开始。