1

I don't understand how the following test can pass. I tried it in my application and it fails.

The entry point is the description 'when called by the owner'.

In this function two test cases are run. Before each test case the token with tokenId is transferred to the address stored in this.to. After transferring the token approval is deleted.

The test case transfers the ownership of the given token ID to the given address because it tests the new owner of the contract.

The second test 'clears the approval for the token ID'will alway fail because the transferFunction in the beforeEach function is called again but the token doesn't belong to owneranymore.

I'm wondering if the test framework is supposed to behave differently and should delete the state before running a test case. This is not happening with my setup (ganache-cli@6.1.0, Truffle v4.1.11 (core: 4.1.11, Solidity v0.4.24 (solc-js), Mocha 2.5.3 )

beforeEach(async function () {
  this.to = accounts[1];
  await this.token.approve(approved, tokenId, { from: owner });
  await this.token.setApprovalForAll(operator, true, { from: owner });
});

const transferWasSuccessful = function ({ owner, tokenId, approved }) {
  it('transfers the ownership of the given token ID to the given address', async function () {
    const newOwner = await this.token.ownerOf(tokenId);
    newOwner.should.be.equal(this.to);
  });

  it('clears the approval for the token ID', async function () {
    const approvedAccount = await this.token.getApproved(tokenId);
    approvedAccount.should.be.equal(ZERO_ADDRESS);
  });
...
}

const shouldTransferTokensByUsers = function (transferFunction) {
  describe('when called by the owner', function () {
    beforeEach(async function () {
      ({ logs } = await transferFunction.call(this, owner, this.to, tokenId, { from: owner }));
    });
    transferWasSuccessful({ owner, tokenId, approved });
  });
1

It works because a new instance of the contract is created for each test case. This happens in an outside beforeEach function which is called before every single test case is run.

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.