Quick Start Tutorial
This guide will walk you through setting up a new Hardhat project, adding solidity-coverage
, and running your first coverage report.
Step 1: Set up a Hardhat Project
If you don't have a Hardhat project, create one:
npx hardhat init
Follow the prompts to create a sample project.
Step 2: Install solidity-coverage
Add the plugin as a development dependency:
npm install --save-dev solidity-coverage
# or
yarn add --dev solidity-coverage
Step 3: Configure Hardhat
Load the plugin in your hardhat.config.js
file:
require("@nomicfoundation/hardhat-toolbox");
require("solidity-coverage");
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
solidity: "0.8.24",
};
Step 4: Write a Simple Contract
If you created a sample project, you already have a Lock.sol
contract. If not, create a file contracts/Simple.sol
:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Simple {
uint private value;
function setValue(uint _value) public {
value = _value;
}
function getValue() public view returns (uint) {
return value;
}
}
Step 5: Write a Test
Create a test file test/Simple.js
to test your contract:
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("Simple", function () {
it("should set and get the value", async function () {
const Simple = await ethers.getContractFactory("Simple");
const simple = await Simple.deploy();
await simple.waitForDeployment();
await simple.setValue(42);
expect(await simple.getValue()).to.equal(42);
});
});
Step 6: Run Coverage
Now, run the coverage task from your project's root directory:
npx hardhat coverage
Step 7: View the Report
You will see a coverage summary printed to your console, which looks something like this:
----------------|----------|----------|----------|----------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------|----------|----------|----------|----------|-------------------
contracts/ | 100 | 100 | 100 | 100 |
Simple.sol | 100 | 100 | 100 | 100 |
----------------|----------|----------|----------|----------|-------------------
All files | 100 | 100 | 100 | 100 |
----------------|----------|----------|----------|----------|-------------------
For a more detailed, interactive view, open the HTML report generated in the coverage/
directory:
open coverage/index.html
This report will show you which specific lines of your code were executed by your tests.