0Pricing
Web3 & DApp Development Fundamentals · Урок

Фикстуры

Переиспользуемая настройка тестов

«Фикстуры» — бесплатный урок Web3 & DApp Development Fundamentals на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web3 & DApp Development Fundamentals, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

The Setup Problem

Many tests need the same starting state — a deployed contract, funded accounts, initial config. Repeating this setup in every beforeEach is slow and repetitive.

Fixtures solve this by running setup once and snapshotting the result.

What Is loadFixture

Hardhat provides loadFixture in its network helpers. The first time it runs a fixture function and takes an EVM snapshot. Later calls simply revert to that snapshot instead of re-running everything.

This makes tests both fast and perfectly isolated.

Importing the Helper

Import loadFixture from the network helpers package (included in the Toolbox):

const { loadFixture, } = require("@nomicfoundation/hardhat-network-helpers"); const { expect } = require("chai"); const { ethers } = require("hardhat");
const {
  loadFixture,
} = require("@nomicfoundation/hardhat-network-helpers");
const { expect } = require("chai");
const { ethers } = require("hardhat");

Writing a Fixture Function

A fixture is an async function that performs setup and returns the objects tests need:

async function deployTokenFixture() { const [owner, alice] = await ethers.getSigners(); const Token = await ethers.getContractFactory("Token"); const token = await Token.deploy(); return { token, owner, alice }; }
async function deployTokenFixture() {
  const [owner, alice] = await ethers.getSigners();
  const Token = await ethers.getContractFactory("Token");
  const token = await Token.deploy();
  return { token, owner, alice };
}

Using a Fixture in a Test

Call loadFixture at the start of each test and destructure what you need:

it("assigns supply to owner", async function () { const { token, owner } = await loadFixture(deployTokenFixture); expect(await token.balanceOf(owner.address)) .to.equal(await token.totalSupply()); });
it("assigns supply to owner", async function () {
  const { token, owner } = await loadFixture(deployTokenFixture);
  expect(await token.balanceOf(owner.address))
    .to.equal(await token.totalSupply());
});

Why Fixtures Are Fast

Re-running deployment for every test is expensive. With fixtures:

  • The setup transactions execute only once.
  • Subsequent tests revert the EVM to the snapshot — a near-instant operation.

Large suites can run dramatically faster than equivalent beforeEach setups.

Isolation Guarantee

Because each loadFixture call reverts to the original snapshot, tests cannot leak state into each other. One test transferring tokens does not affect the next test's starting balances.

This isolation is what makes test results reliable and order-independent.

Fixtures with Parameters

loadFixture takes a function reference, not a call, so it cannot accept arguments directly. To vary setup, define multiple fixtures:

async function deployPausedFixture() { const base = await deployTokenFixture(); await base.token.pause(); return base; }

Each variant gets its own snapshot.

async function deployPausedFixture() {
  const base = await deployTokenFixture();
  await base.token.pause();
  return base;
}

Fixtures vs beforeEach

When should you use each?

  • loadFixture — preferred for deployment-heavy setup; faster and snapshot-based.
  • beforeEach — fine for trivial setup or when you need per-test side effects.

The Hardhat team recommends fixtures for most contract deployment setup.

A Common Pitfall

Do not call the fixture function directly inside loadFixture:

// Wrong: passes the result, not the function await loadFixture(deployTokenFixture()); // Right: passes the function reference await loadFixture(deployTokenFixture);

Passing the reference lets Hardhat manage the snapshot lifecycle.

// Wrong: passes the result, not the function
await loadFixture(deployTokenFixture());

// Right: passes the function reference
await loadFixture(deployTokenFixture);

Sharing Fixtures Across Files

You can move a fixture into its own module and import it wherever needed:

// fixtures.js module.exports = { deployTokenFixture }; // in a test file const { deployTokenFixture } = require("./fixtures"); const { token } = await loadFixture(deployTokenFixture);

The snapshot caching still works across files in the same run.

// fixtures.js
module.exports = { deployTokenFixture };

// in a test file
const { deployTokenFixture } = require("./fixtures");
const { token } = await loadFixture(deployTokenFixture);

Quick Check

Test your understanding of fixtures.

Recap

You learned reusable test setup with fixtures.

  • loadFixture runs setup once and snapshots the EVM.
  • Later calls revert to the snapshot — fast and fully isolated.
  • A fixture is an async function returning the objects tests need.
  • Pass the function reference, never call it.
  • Define multiple fixtures for different starting states.

Часто задаваемые вопросы

Урок «Фикстуры» бесплатный?

Да — полный текст урока «Фикстуры» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Web3 & DApp Development Fundamentals, подпишись на CoddyKit PRO. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.

Чему я научусь в уроке «Фикстуры»?

Переиспользуемая настройка тестов Ты практикуешь Web3 & DApp Development Fundamentals с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Web3 & DApp Development Fundamentals?

Предыдущий опыт не требуется. Web3 & DApp Development Fundamentals на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Фикстуры»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Web3 & DApp Development Fundamentals?

Да. Каждый урок Web3 & DApp Development Fundamentals включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Написание тестов
  2. Тестирование откатов и событий
  3. Покрытие и отчёты о расходе газа
  4. Фикстуры
← Назад к Web3 & DApp Development Fundamentals