Running tests in Hardhat is a straightforward process that helps ensure your smart contracts function as expected. This guide will walk you through the steps to run tests using Hardhat, including setting up your testing environment and executing your test scripts.

1. Setting Up Your Hardhat Project

Before you can run tests, ensure you have a Hardhat project set up. If you haven't done this yet, follow these steps:

  • Create a new directory for your Hardhat project:
  • mkdir my-hardhat-project
    cd my-hardhat-project
  • Initialize a new npm project:
  • npm init -y
  • Install Hardhat:
  • npm install --save-dev hardhat
  • Run Hardhat to create a new project:
  • npx hardhat

    Select "Create an empty hardhat.config.js" when prompted.

2. Writing Tests

Next, create a test directory in your project root and add a test file. For example, create a file named Token.test.js in the test directory:

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

describe("Token contract", function () {
let token;
let owner;
let addr1;

beforeEach(async function () {
const Token = await ethers.getContractFactory("Token");
token = await Token.deploy(1000);
[owner, addr1] = await ethers.getSigners();
});

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

it("Should transfer tokens between accounts", async function () {
await token.transfer(addr1.address, 50);
expect(await token.balanceOf(addr1.address)).to.equal(50);
});
});

3. Running Your Tests

To run your tests, open your terminal and navigate to your Hardhat project directory. Then, execute the following command:

npx hardhat test

This command will look for all files in the test directory that end with npm init -y0 and execute the tests within those files. You should see output similar to the following:

npm init -y1

4. Running Specific Tests

If you want to run a specific test file, you can specify the path to the test file:

npm init -y2

5. Running Tests with a Custom Network

If you want to run your tests on a custom network (like a local Hardhat network), you can start the Hardhat network in a separate terminal window:

npm init -y3

Then, in another terminal, run your tests against this network:

npm init -y4

6. Viewing Test Coverage

To check the coverage of your tests, you can use the npm init -y5 plugin. First, install it:

npm init -y6

Then, update your npm init -y7 file to include the plugin:

npm init -y8

Now you can run the coverage report with:

npm init -y9

Conclusion

Running tests in Hardhat is an essential part of the development process for smart contracts. By following the steps outlined in this guide, you can ensure your contracts are functioning correctly and securely. Regular testing helps catch bugs early and improves the overall quality of your code.