I've written some truffle tests that interact with the account balances. Example:

A contract transfers X amount of ether from account A to account B.

Surprisingly the state of the accounts (especially the balances) are not reset between test cases. Meaning tests that test balance transfers cannot be deterministic. Is there a way around this?


Yeah, if you want deterministic tests you need to use testrpc with some special params before each test.

Something like:

let web3 = new Web3('ws://localhost:8546');
let testrpc;

before(function(done) {
  testrpc = TestRPC.server({
    ws: true,
    gasLimit: 5800000,
    total_accounts: 10,
    seed: 1

  testrpc.listen(8546, '');

More info at: https://github.com/ethereumjs/testrpc


When running Truffle JavaScript tests using Ganache or ganache-cli, there is nothing to do: Truffle resets the blockchain state between each test. The initial snapshot is done just after loading the contracts.

More precisely, the state is reset before each contract (Truffle replacement for mocha's describe). For example:

var MyContract = artifacts.require("./MyContract.sol");

contract('MyContract - A', function(accounts) {
  before("Setup", async function () {
    // Suppose balance of accounts[0] == 100ETH

  it("should do Alpha", async function() {
    // Balance of accounts[0] == 100ETH
    // Balance of accounts[0] == 99ETH

  it("should do Beta", async function() {
    // Balance of accounts[0] == 99ETH,
    // because state is *not* reset between 'it'

contract('MyContract - B', function(accounts) {
  it("should do Alpha", async function() {
    // Balance of accounts[0] == 100ETH again,
    // because state is reset between 'contract'

This is something you can track in Ganache logs. Look for evm_snapshot and evm_revert.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.