0

I am trying to write test for erc20 token and when I try to revert the transaction if the sender has insufficient balance, it is throwing an error.

enter image description here

Solidity code for transfer function

  function _transfer(address _from, address _to, uint256 _amount) internal {
    require(balanceOf[_from] >= _amount);
    require(balanceOf[_to] + _amount >= balanceOf[_to]);
    balanceOf[_to] += _amount;
    balanceOf[_from] -= _amount;
    emit Transfer(_from, _to, _amount);
  }
  
  function transfer(address _to, uint256 _amount) public returns(bool) {
    require(msg.sender != address(0) && _to != address(0), "Address cannot be zero");
    _transfer(msg.sender, _to, _amount);
    return true;
  }

And the code for test:

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Blue20", () => {
  let Token, token, owner, addr1, addr2;
  beforeEach(async () => {
    Token = await ethers.getContractFactory("blue20");
    token = await Token.deploy();
    [owner, addr1, addr2, _] = await ethers.getSigners();
  });

  describe("Deployment", () => {
    it("Checking the deployment processs", async () => {
      expect(await token.owner()).to.equal(owner.address);
    });

    it("Should assign the total tokens to the owner", async () => {
      const ownerBalance = await token.balance(owner.address);
      expect(await token.totalSupply()).to.equal(ownerBalance);
    });
  });

  describe("Transactions", () => {
    it("Succesfully transfer the tokens and verify", async () => {
      await token.transfer(addr1.address, 100);
      let addr1Balance = await token.balance(addr1.address);
      expect(await addr1Balance).to.equal(100);

      await token.connect(addr1).transfer(addr2.address, 100);
      let addr2Balance = await token.balance(addr2.address);
      expect(addr2Balance).to.equal(100);
    });

    it("Should fail if sender doesn't have enough tokens", async () => {
      expect(
        await token.connect(addr1).transfer(owner.address, 1)
      ).to.be.revertedWith("Not enough Tokens");
    });
  });
});

I use hardhat as development environment.

1 Answer 1

0

A couple of things you should change in your test. First the await keyword should be outside the expect. Secondly, for getting the address from signers, you should use getAddress(). Try changing your test to:

it("Should fail if sender doesn't have enough tokens", async () => {
  await expect(token.connect(addr1).transfer(owner.getAddress(), 1) ).to.be.revertedWith("Not enough Tokens");
});

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.