0Pricing
Web3 & DApp Development Fundamentals · Lekcja

Pisanie testów

Mocha i Chai

Pisanie testów to bezpłatna lekcja Web3 & DApp Development Fundamentals na CoddyKit. To lekcja 1 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Web3 & DApp Development Fundamentals, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Web3 & DApp Development Fundamentals zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Why Test Contracts

Smart contracts are immutable once deployed and often hold real value. A single bug can be unrecoverable, so thorough testing is essential.

  • Catch logic errors before deployment.
  • Document expected behavior.
  • Guard against regressions when refactoring.

Mocha and Chai

Hardhat uses Mocha as the test runner and Chai for assertions, both included in the Toolbox.

  • describe groups related tests.
  • it defines a single test case.
  • expect makes assertions about values.

Tests live in the test/ folder.

A First Test File

A basic test imports ethers and Chai, then deploys and checks the contract:

const { expect } = require("chai"); const { ethers } = require("hardhat"); describe("Greeter", function () { it("returns the initial greeting", async function () { const Greeter = await ethers.getContractFactory("Greeter"); const greeter = await Greeter.deploy(); expect(await greeter.greeting()).to.equal("Hello, Hardhat"); }); });
const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Greeter", function () {
  it("returns the initial greeting", async function () {
    const Greeter = await ethers.getContractFactory("Greeter");
    const greeter = await Greeter.deploy();
    expect(await greeter.greeting()).to.equal("Hello, Hardhat");
  });
});

Running Tests

Run the whole suite with:

npx hardhat test

Hardhat compiles contracts first, spins up a fresh in-process network, and reports passing and failing tests. You can pass a path to run just one file.

npx hardhat test

Async and await

Almost every contract interaction is asynchronous because it talks to the network. Always await deployments and calls:

it("works", async function () { const c = await Factory.deploy(); await c.waitForDeployment(); const value = await c.getValue(); expect(value).to.equal(0); });

Forgetting await is the most common cause of confusing test results.

it("works", async function () {
  const c = await Factory.deploy();
  await c.waitForDeployment();
  const value = await c.getValue();
  expect(value).to.equal(0);
});

Common Chai Matchers

Chai gives expressive matchers for assertions:

  • .to.equal(x) — strict equality.
  • .to.be.true / .to.be.false — booleans.
  • .to.be.gt(n) — greater than.
  • .to.deep.equal([...]) — array/object equality.
expect(await token.balanceOf(user)).to.equal(100);
expect(await token.balanceOf(user)).to.equal(100);

Working with Signers

getSigners returns test accounts you can use as different users:

const [owner, alice, bob] = await ethers.getSigners(); await token.connect(alice).transfer(bob.address, 50);

connect(signer) sends the next call as that account, which is key for testing access control.

const [owner, alice, bob] = await ethers.getSigners();
await token.connect(alice).transfer(bob.address, 50);

BigInt Values

Numbers on-chain are large integers. In ethers v6 they are JavaScript BigInt values. Compare them carefully:

const supply = await token.totalSupply(); expect(supply).to.equal(ethers.parseEther("1000"));

Use parseEther and formatEther to convert between human and on-chain units.

const supply = await token.totalSupply();
expect(supply).to.equal(ethers.parseEther("1000"));

Setup with beforeEach

Use beforeEach to deploy a fresh contract for every test, ensuring isolation:

let token; beforeEach(async function () { const Token = await ethers.getContractFactory("Token"); token = await Token.deploy(); });

Each it then starts from a clean, identical state.

let token;
beforeEach(async function () {
  const Token = await ethers.getContractFactory("Token");
  token = await Token.deploy();
});

Reading Test Output

A green checkmark means the test passed; a red cross with a diff shows what failed. Mocha prints the describe and it labels, so write descriptive names:

  • Good: it("reverts when caller is not owner")
  • Vague: it("test1")

Running a Single Test

While developing you often want to focus on one test. Use Mocha's .only:

it.only("reverts when not owner", async function () { // only this test runs });

You can also run a single file with npx hardhat test test/Token.js. Remember to remove .only before committing.

it.only("reverts when not owner", async function () {
  // only this test runs
});

Quick Check

Test your understanding of writing contract tests.

Recap

You learned to write contract tests.

  • Hardhat uses Mocha (describe/it) and Chai (expect).
  • Tests live in test/ and run with npx hardhat test.
  • Always await async contract calls.
  • getSigners + connect simulate different users.
  • On-chain numbers are BigInt; use parseEther/formatEther and beforeEach for clean setup.

Często zadawane pytania

Czy lekcja „Pisanie testów” jest bezpłatna?

Tak — pełny tekst „Pisanie testów” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Web3 & DApp Development Fundamentals, przejdź na CoddyKit PRO. Kurs Web3 & DApp Development Fundamentals zawiera 4 lekcji w sumie.

Co nauczysz się w „Pisanie testów”?

Mocha i Chai Ćwiczysz Web3 & DApp Development Fundamentals z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Web3 & DApp Development Fundamentals?

Nie wymagamy żadnego doświadczenia. Web3 & DApp Development Fundamentals w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 1 z 4.

Ile czasu zajmuje lekcja „Pisanie testów”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Web3 & DApp Development Fundamentals?

Tak. Każda lekcja Web3 & DApp Development Fundamentals zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Pisanie testów
  2. Testowanie revertów i zdarzeń
  3. Pokrycie i raporty gas
  4. Fixtures
← Powrót do Web3 & DApp Development Fundamentals