4

What's the difference in using new() or deployed() when creating a contract instance to use in Truffle unit tests? Should I use

// VERSION A
it("should work", async () => {
  let instance = await MyContract.deployed();
  :
});

or

// VERSION B
it("should work", async () => {
  let instance = await MyContract.new();
  :
});
5

deployed behaves like a singleton. It will look if there is already an instance of the contract deployed to the blockchain via deployer.deploy. The information about which contract has which address on which network is stored in the build folder. new will always create a new instance.

It depends on your testcase, but I prefer not using deployed in unit tests in order to avoid side-effects and better isolate the unit tests.

Some unit tests will require instantiating multiple instances of a smart contract and deploying each of them. In this case, new is the only option as deployed simply retrieves the same already-deployed contract each time.

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.