[英]how to create new ethereum/solidity contract for each test in javascript/truffle
I have written an ethereum smart-contract in the Solidity language. 我已经写在了复仇的智能合同密实度的语言。 In order to test things, I can run a local node using Ganache and deploy my contract on it using truffle migrate
. 为了测试的东西,我可以使用运行本地节点伽纳彻和使用上我的合同部署truffle migrate
。
I want to test my contract using JavaScript. 我想使用JavaScript测试我的合同。 I want to create a new instance of my contract for each test. 我想为每个测试创建合同的新实例。
I created a test file tests/test.js
in my project: 我在项目中创建了一个测试文件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)
})
})
I run it with truffle test
. 我用truffle test
运行它。 It's basically Mocha , but truffle defines artifacts
for you with a JavaScript connection to the smart contracts. 它基本上是Mocha ,但是松露通过与智能合约的JavaScript连接为您定义artifacts
。
The truffle contract
function is almost the same as Mocha's describe
function, with a small change that I don't understand! 松露contract
功能几乎与 Mocha的describe
功能相同 ,只是有一点我不明白的变化! I assumed that contract
would make my contract new each time. 我以为contract
每次都会使我的合同更新。 It doesn't. 没有。 Perhaps I can use something like new Round()
instead of Round.deployed()
, but I just don't know how. 也许我可以使用诸如new Round()
类的东西来代替Round.deployed()
,但是我只是不知道如何。
The solution does not have to use truffle. 该解决方案不必使用松露。
Please note that .new
and .deployed
are not the same. 请注意, .new
和.deployed
不相同。 See what I've found here . 看看我在这里发现了什么。
Follow this example and it should solve your problem: 请按照以下示例操作,它应该可以解决您的问题:
// 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]);
});
});
The .new
keyword will deploy an instance of your contract in a new context. .new
关键字将在新的上下文中部署合同的实例。
But, .deployed
will actually use the contract that you have deployed earlier ie when you are using truffle migrate
command. 但是, .deployed
实际上将使用您,当您使用早期即部署合同truffle migrate
命令。
In the context of unit test, it's better to use .new
so that you will always start with fresh contract. 在单元测试的上下文中,最好使用.new
以便您始终从新合同开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.