1

When I try to test my contract in truffle test javascript, how is it different to create new instant for my contract by instant = await myContract.deployed() and instant = await myContract.new()? is it same? It seems like I have to use deployed in side beforeEach function as follows,

  beforeEach('for each test...', async function() {
    instant = await myContract.deployed();
  });

every time,to generate new instant then I have to use new(), If I just want to use the same instant in my each unit tests, then I have to use deployed()? Please correct me if I am wrong.

4

You are right.

Truffle test's deployed and new are from truffle-contract. If you look at the doc:

deployed(): Create an instance of MyContract that represents the default address managed by MyContract.

new(): Deploy a new version of this contract to the network, getting an instance > of MyContract that represents the newly deployed instance.

AFAIK, when you run truffle test, initially it will go through your migration script, and migrate new contracts onto the node you have specified in truffle.js. When you get a instance from deployed(), you are actually getting a javascript instance from one of these initially deployed contracts.

On the other hand, when you get a instance from new(), it will newly deploy the contract onto the network, and return the corresponding javascript instance.

So, if your contract has states, and the results of tests are dependent on the sequence they are run, then you'll need to use new() in beforeEach to get a clean room environment for individual tests.

Note that if you use contract() function, then before each contract() function is run, your contracts are redeployed to the running Ethereum client so the tests within it run with a clean contract state.

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.