overview
After developing an Ethereum smart contract using the Solidity language, I utilized Ganache to deploy my contract for testing purposes. However, in order to conduct tests effectively, I need to create a new instance of my contract using JavaScript.
approach
To achieve this, I proceeded to write a test script named tests/test.js
within my project directory:
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)
})
}
Running the test with truffle test
(which is based on Mocha), revealed a discrepancy in how the contract instances are handled. Despite utilizing the truffle contract
function similar to Mocha's describe
, there was an unexpected behavior where the contract was not created anew each time.
I explored the possibility of using new Round()
instead of Round.deployed()
, but am uncertain about its implementation. The key is to ensure that each test case operates on a fresh instance of the contract.
While my preference is to resolve this issue without depending solely on truffle, any alternative solution that achieves the desired outcome is welcome.