Fix Hardhat Test with Ethers Errors
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.
Right
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 testfor 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro