0
0
Blockchain / Solidityprogramming~5 mins

Hardhat testing setup in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Hardhat testing setup
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The beforeEach hook runs before every test, redeploying the contract.
  • How many times: Once per test case inside the describe block.
How Execution Grows With Input

As the number of test cases grows, the setup runs before each one, increasing total time.

Input Size (number of tests)Approx. Operations (deployments)
1010 deployments
100100 deployments
10001000 deployments

Pattern observation: The total setup time grows directly with the number of tests.

Final Time Complexity

Time Complexity: O(n)

This means the total testing time grows in a straight line as you add more tests.

Common Mistake

[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.

Interview Connect

Understanding how test setup time grows helps you write efficient tests and shows you can think about performance in real projects.

Self-Check

What if we moved the contract deployment from beforeEach to before? How would the time complexity change?