Hardhat testing setup in Blockchain / Solidity - Time & Space Complexity
When running tests with Hardhat, it's important to understand how the time taken grows as the number of tests or contracts increases.
We want to know how the testing time changes when we add more test cases or contracts.
Analyze the time complexity of the following Hardhat test setup code.
const { expect } = require("chai");
describe("Token contract", function () {
let Token, token, owner, addr1;
beforeEach(async function () {
Token = await ethers.getContractFactory("Token");
token = await Token.deploy();
[owner, addr1] = await ethers.getSigners();
});
it("Should assign total supply to owner", async function () {
const ownerBalance = await token.balanceOf(owner.address);
expect(await token.totalSupply()).to.equal(ownerBalance);
});
});
This code sets up a test for a token contract, deploying it before each test and checking balances.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
beforeEachhook runs before every test, redeploying the contract. - How many times: Once per test case inside the
describeblock.
As the number of test cases grows, the setup runs before each one, increasing total time.
| Input Size (number of tests) | Approx. Operations (deployments) |
|---|---|
| 10 | 10 deployments |
| 100 | 100 deployments |
| 1000 | 1000 deployments |
Pattern observation: The total setup time grows directly with the number of tests.
Time Complexity: O(n)
This means the total testing time grows in a straight line as you add more tests.
[X] Wrong: "Running more tests won't affect setup time much because deployment is fast."
[OK] Correct: Each test runs the setup separately, so deployment time adds up and grows with the number of tests.
Understanding how test setup time grows helps you write efficient tests and shows you can think about performance in real projects.
What if we moved the contract deployment from beforeEach to before? How would the time complexity change?