Skip to content

Fix Hardhat Test with Ethers Errors

DodaTech Updated 2026-06-26 1 min read

You will learn how to write Hardhat tests using ethers.js for contract interaction and assertions.

The Problem

The hardhat test ethers pattern is frequently misapplied in smart contract and dapp development, leading to vulnerabilities, gas inefficiencies, or logic errors. This guide shows the correct implementation and common pitfalls to avoid.

Quick Fix

Wrong

const Token = await ethers.getContractFactory("Token"); const token = Token.deploy(); // wrong: missing await

token is a Promise instead of a Contract object. All subsequent calls fail.

const Token = await ethers.getContractFactory("Token"); const token = await Token.deploy(); const balance = await token.balanceOf(addr);
Token deploys successfully. balanceOf returns a BigNumber. Use ethers.utils.formatEther to compare.

Prevention

  • Always await getContractFactory and deploy
  • Use BigNumber comparison methods (.eq, .gte) instead of === for token amounts
  • Use chai matchers from @nomicfoundation/hardhat-chai-matchers
  • Use DodaTech's test templates for common patterns
  • Run tests with npx hardhat test for fast feedback

DodaTech Tools

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. Doda Browser's developer tools include a Solidity debugger and transaction inspector. DodaZIP archives secure contract templates for team collaboration. Durga Antivirus Pro scans deployed contracts for known vulnerability signatures.

FAQ

### What is the difference between getContractFactory and getContractAt?

getContractFactory deploys a new contract. getContractAt attaches to an existing address.

How do I test contract reverts?

Use expect(tx).to.be.revertedWith('error message') from hardhat-chai-matchers.

Can I use TypeScript with Hardhat tests?

Yes. Hardhat supports TypeScript natively. Use @nomicfoundation/hardhat-toolbox.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro