【发布时间】:2018-10-07 16:19:55
【问题描述】:
背景
我用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,并通过JavaScript 连接到智能合约。
truffle contract 函数 is almost the same 和 Mocha 的 describe 函数一样,有一点我看不懂的小改动!我假设contract 每次都会使我的合同变得新。它没有。也许我可以使用new Round() 之类的东西来代替Round.deployed(),但我就是不知道怎么做。
解决方案没有使用松露。
【问题讨论】:
-
你确定不是同一份合同吗?在他们的网站上,他们声称这将是每个
describe函数中的一个新合约实例。你怎么知道是同一个实例? -
查看这个 Twitter 线程 — twitter.com/zulhhandyplast/status/1026181801239171072
-
@nikosfotiadis 我敢肯定。我知道的方式可能与问题无关,但是如果您尝试两次质押相同的金额,则合同将出错。因此,在我上面输入的示例中,当我希望不会出错时,我得到了一个错误。
-
@ZulhilmiZainudin 是的,使用
.new()而不是.deployed()就像一个魅力!这真的应该添加到松露文档中。您可以将其发布为答案吗? -
我很高兴它有帮助。我已经发布了我的答案。感谢您是否可以投票并接受它。
标签: javascript testing solidity smartcontracts truffle