Solidity – Comprehensive Guide to Unit Testing with JavaScript

javascriptsolidityunittesting

I want to test these 3 different require in my mint function with Javascript.

function mint(uint256 _mintAmount) public payable {
    require(_mintAmount > 0, "need to mint at least 1 NFT");
    require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded");
    require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");

I'm really new to testing so I tried something like this. obviously its wrong but how can I test that it requires more than 0 _mintAmount in a function like this

it('mint amount', async () =>{
    _mintAmount > 0;
    _mintAmount <= maxMintAmount;
    supply + _mintAmount <= maxSupply;
})

also tried something like this:

also tried something like this:

it('mint amount', async () =>{
    var _mintAmount = await NFT.mint(_mintAmount);
    assert.equal(_mintAmount, _mintAmount > 0);     
})

Best Answer

In the unit-testing you commonly want to make sure that you get the output that you were expecting. You already have all the checks you wanted in the mint() function, now in the unit tests lets make sure that they work, ie mint(0) would return "need to mint at least 1 NFT"

You can do this by using assert.equal()

it('mint amount', async function () {
            try { 
               await myContract.mint.sendTransaction(0);
            } catch (err) {
                 assert.equal("need to mint at least 1 NFT", err.reason);
            }
});

By using try and catch to get the revert error messages you can check for expected output for any input you want.

Related Topic