7

This is my test, which fails and it should pass

  it('Should not allow 0 address to be added', async () => {
    await expect(greeter.addWhitelistAddress('0x0')).to.be.revertedWith(
      'Invalid address'
    );
  });

and this is my function

   function addWhitelistAddress(address _wlAddress)
        public
    {
        require(_wlAddress != address(0), 'Invalid address');
        whitelisted[_wlAddress] = true;
    }
1

2 Answers 2

8

You can use ethers constants.

In hardhat tests, ethers lib are imported by default, so you don't need to add the require sentence.

Happy coding!

     it('Should not allow 0 address to be added', async () => {
        await expect(greeter.addWhitelistAddress(ethers.constants.AddressZero)).to.be.revertedWith(
          'Invalid address'
        );
      });
2
  • I prefer to define my own constant for that: export const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';. It's much more accessible compared to ethers.constants.AddressZero.
    – asologor
    Feb 23, 2023 at 17:10
  • It's ethers.ZeroAddress in ethers v6 Apr 9 at 8:51
1

You can use openzeppelin's test library for this.

it("Should return an error when address 0 is entered", async function () {
    const {
        constants,
        expectRevert,
    } = require('@openzeppelin/test-helpers');
  
    const AWLContract = await ethers.getContractFactory("AddWhiteList");
    const addWhiteList = await AWLContract.deploy();

    console.log(constants.ZERO_ADDRESS);
    await addWhiteList.deployed();
   
    await expectRevert(
        addWhiteList.addWhitelistAddress(constants.ZERO_ADDRESS),
        'Invalid address',
    );

});

So you should change the quotes in the messages with "Invalid address".

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.