1

I wrote a smart contract. now, I am writing tests in truffle .

the code is gonna look like this.

contract('contract', accounts => {
  it("test1", () => {

  })


  it("test2", () => {
    
  })

  it("test3", () => {
    
  })
  
})

Now, let's say I transferred 30 coins from accounts[1] to accounts[2] in test1 and in test1, I had a check for that and it asserted well. Now, in test2, I am testing different function, but that function still relies on the balance of accounts[1]. Now, it means that I should know what the balance was after the test1 ran. This is still fine, but then, in test3, I should know what the balance was for accounts[1] after test2 was run.

Problem 1: if some other developer comes and looks at this file, he can't really change something in test3, because if so, then he really has to know the results of accouns[1] from test2 which implies that he has to know results from test1. So, He has to understand everything..

Problem 2: If we decide that each it test of mocha is not dependent on each other, that means that, for each test, we should put each test in contract('contract') in order for truffle to start redeploying from scratch for each test. This is too time consuming and also, each test will become TOO BIG. because now, test3 should include all the functions from solidity contract while in Problem 1, it would only have to include the function that it's going to test and test2 would take care of the previous dependent functions.

What's your recommendation ? or what am I doing wrong ?

1 Answer 1

1

Truffle tests are based on mocha framework so you can use similar approach.

  • Create multiple contract sections for the same contract. Each test will be independent.

    contract('token - balances', () => { ... })
    
    contract('token - transfers', () => { ... })
    
    contract('token - minting', () => { ... })
    
  • Use tests fixtures before, after, beforeEach, afterEach to customize tests. For example you can initialize your contracts on before and then reset to known state at beforeEach so the next test will have a predictable starting point.

    contract('token - balances', () => {
      before(() => {
        // Execute once before all tests
      })
    
      afterEach(() => {
        // Execute every time after each test
      })
    
      it('test1', () => {
      })
    });
    
1
  • 1
    Great answer! If you are only testing against ganache, you can use evm_snapshot and evm_revert in your beforeEach and afterEach to reset state in between each test. Commented Dec 10, 2020 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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