Search code examples
soliditytruffleweb3js

Understanding truffle test


I am following a tutorial to create a smart contract using truffle. I would like to have a better understanding about the test created in the tutorial.

This is one of the tests:

it("increases myDonationsCount", async () => {
  const currentDonationsCount = await fundraiser.myDonationsCount(
    {from: donor}
  );

  await fundraiser.donate({from: donor, value});

  const newDonationsCount = await fundraiser.myDonationsCount(
    {from: donor}
  );

  assert.equal(
    1,
    newDonationsCount - currentDonationsCount,
    "myDonationsCount should increment by 1");
})

where does this object come from? {from: donor, value}

And for this test:

it("throws an error when called from a different account", async () =>{
  try {
    await fundraiser.setBeneficiary(newBeneficiary, {from: accounts[3]});
    assert.fail("withdraw was not restricted to owners")
  } catch(err) {
    const expectedError = "Ownable: caller is not the owner"
    const actualError = err.reason;
    assert.equal(actualError, expectedError, "should not be permitted")
  }
})

In the 3rd line from the above test they are passing 2 parameters fundraiser.setBeneficiary(newBeneficiary, {from: accounts[3]});. How is this possible if the original function only receives one?

The function:

function setBeneficiary(address payable _beneficiary) public onlyOwner {
    beneficiary = _beneficiary;
}

Solution

  • It's the transaction params.

    Truffle allows you to override the default transaction params by specifying the overrides in the last argument, after you've passed all arguments defined in the Solidity function.

    Docs: https://www.trufflesuite.com/docs/truffle/getting-started/interacting-with-your-contracts#making-a-transaction