6

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();
  :
});

1 Answer 1

7

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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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