Testing does not reset state
contract Test {
uint[] a;
function length() public view returns (uint) {
return a.length;
}
function add(uint val) public {
a.push(val);
}
}
var Test = artifacts.require("Test");
contract('Test', function(accounts) {
it("test 0", async function() {
var t = await Test.deployed();
var l = await t.length.call();
assert.equal(l.toNumber(), 0, 'array should be empty');
});
it("test 1", async function() {
var t = await Test.deployed();
await t.add(1);
});
it("test 2", async function() {
var t = await Test.deployed();
var l = await t.length.call();
assert.equal(l.toNumber(), 0, 'array should be empty');
});
});
all tests should pass
Contract: Test test 2:
AssertionError: array should be empty: expected 1 to equal 0
Truffle tests dont reset state within the same file, if this is an issue for you, you can use a 'beforeEach' hook and specify a function which creates a new instance of your contract using 'MyContract.new([param1],[param2]...)'
Hi @timothywangdev! @JackPickering is correct. You can see some nice examples of the beforeEach pattern he's describing at the Cryptokitties contract repository here.
By design Truffle resets the state or "reverts" between each contract suite - e.g. each block of tests wrapped in Truffle's contract test abstraction.
Closing because this is intended behavior.
This might want to be reconsidered @cgewecke . For instance, when using the evm_increaseTime feature, the timestamp of all subsequent blocks will be increased by the previous value, which makes testing timestamp based functionalities quite cumbersome. This is one example, but I am sure there are others. Ideally, one could have the option of starting from scratch if desired, even it less efficient.
Most helpful comment
This might want to be reconsidered @cgewecke . For instance, when using the
evm_increaseTimefeature, the timestamp of all subsequent blocks will be increased by the previous value, which makes testing timestamp based functionalities quite cumbersome. This is one example, but I am sure there are others. Ideally, one could have the option of starting from scratch if desired, even it less efficient.