I have a test contract with four test functions. Using truffle compile && truffle test.

If I run it as normal, functions 1-3 pass and #4 fails.

If I commend out function #2 then functions 1, 3, 4 all pass.

It is clear that the test functions are not being run independently. How do I make my test functions run independently or otherwise compensate for this situation?

My test cases are all in one Solidity file.

  • And related, why does running truffle and then compile and test multiple times produce different results than quitting and reopening truffle in between each set? – William Entriken Oct 29 '18 at 0:49

You want to clear out whatever happens in the previous test before the next one proceeds. One way is to add a beforeEach or afterEach to make sure you've rest everything in the previous test before moving on to the next one. Another way is to do this within the actual test. Finally, and my preferred way, is to stub ancillary function calls rather than calling them directly. This will require downloading something like the node module sinon.js -- https://sinonjs.org/releases/latest/ and adding stubs to your code. Then you can reset your stubs as you go to ensure you're not polluting future tests. I hope that is helpful!

| improve this answer | |

I think one way to approach this issue is to recreate the variables used in each tests, this is not so much a solidity question, but rather a mocha testing question.

 contract('Testing', accounts => {
 beforeEach(async () => {
    ContractInstance = await erc20token.new("MyStoreFront")

    erc20factoryInstance = await erc20factory.new()
    await ContractInstance.setParent(erc20factoryInstance.address)

Use a beforeeach loop declartion. See https://mochajs.org/#hooks

| improve this answer | |

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.