0

I have a very simple function in my Solidity contract, that I'm trying to test its return value with Hardhat.

    function mintNFT(address _recipient) public returns (uint256)
    {
        uint256 tokenId = calculateTokenID();
        return tokenId;
    }

where tokenId has some logic to generate a uint256. I've added a console.log(tokenId) in the Smart Contract which correctly prints out the tokenId, however, when returned and attempted to test, it comes back as undefined

const { expect } = require('chai');

// Import utilities from Test Helpers
const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');

// Load compiled artifacts
const CONTRACT = artifacts.require('MyContract');

// Start test block
contract('CONTRACT', function ([ owner, other ]) {
  beforeEach(async function () {
    this.contract = await CONTRACT.new();
    await this.contract.initialize();
  });

  it("mintNFT generated a valid token ID", async function () {
    const tokendID = await this.contract.mintNFT();
    expect(tokendID.to.equal(1));
  });

Error:

  1) Contract: DPC
       mintNFT generated a valid token ID:
     TypeError: Cannot read properties of undefined (reading 'equal')
      at Context.<anonymous> (test/DPC_NFT.js:29:24)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)

I've even tried hard-coding the function return to a number, and the test still comes back as undefined. Would greately appreciate your help

3
  • not the answer but tx does not return value. So even if it works correctly it will return a tx response and not the token id
    – Majd TL
    Commented Apr 11, 2022 at 16:07
  • How would you go on about testing something like this? i.e. the returned value of a function?
    – teh0wner
    Commented Apr 11, 2022 at 17:12
  • 2
    @teh0wner The usual solution is to trigger an event and read the event parameters from the transaction receipt. ethereum.stackexchange.com/a/3293
    – Ismael
    Commented Apr 12, 2022 at 4:53

1 Answer 1

1

you are trying to access to property on tokenID that is wrong try this line :

expect(tokenID).to.equal('value you are expect');
1
  • I'm pretty sure that await this.contract.mintNFT(); does not return tokenID, it is a transaction
    – Majd TL
    Commented Apr 12, 2022 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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