Тестирование откатов и событий
Проверка поведения
«Тестирование откатов и событий» — бесплатный урок Web3 & DApp Development Fundamentals на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web3 & DApp Development Fundamentals, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Reverts and Events
Beyond return values, contracts communicate through reverts (transactions that fail and undo state) and events (logs emitted on success).
Good tests assert both: that valid actions emit the right events, and that invalid actions revert with the right reason.
Hardhat Chai Matchers
The Toolbox adds special Chai matchers for Ethereum, available after importing them (the Toolbox does this automatically):
.to.be.revertedWith(...).to.be.revertedWithCustomError(...).to.emit(...).to.changeEtherBalance(...)
Asserting a Revert
To check that a transaction fails, wrap the call (without awaiting it first) and use revertedWith:
await expect(
token.connect(alice).withdraw()
).to.be.revertedWith("Not the owner");The string must match the contract's require message exactly.
await expect(
token.connect(alice).withdraw()
).to.be.revertedWith("Not the owner");Custom Error Reverts
Modern Solidity uses gas-efficient custom errors. Assert them with revertedWithCustomError:
await expect(
vault.connect(alice).withdraw()
).to.be.revertedWithCustomError(vault, "Unauthorized");You pass the contract instance so the matcher can decode the error from the ABI.
await expect(
vault.connect(alice).withdraw()
).to.be.revertedWithCustomError(vault, "Unauthorized");Checking Error Arguments
Custom errors can carry data. Chain withArgs to assert the values:
await expect(
vault.withdraw(amount)
).to.be.revertedWithCustomError(vault, "InsufficientBalance")
.withArgs(amount, balance);This verifies the contract reverted for the exact reason you expect.
await expect(
vault.withdraw(amount)
).to.be.revertedWithCustomError(vault, "InsufficientBalance")
.withArgs(amount, balance);Asserting an Event
Use .to.emit to assert that a transaction emitted an event:
await expect(token.transfer(bob.address, 100))
.to.emit(token, "Transfer");You pass the contract and the event name. This confirms the log was produced.
await expect(token.transfer(bob.address, 100))
.to.emit(token, "Transfer");Checking Event Arguments
Combine emit with withArgs to verify the event payload:
await expect(token.transfer(bob.address, 100))
.to.emit(token, "Transfer")
.withArgs(owner.address, bob.address, 100);This ensures the from, to, and amount fields are exactly correct.
await expect(token.transfer(bob.address, 100))
.to.emit(token, "Transfer")
.withArgs(owner.address, bob.address, 100);Checking Balance Changes
For ETH transfers, changeEtherBalance asserts the net change for an account:
await expect(
() => vault.connect(alice).withdraw()
).to.changeEtherBalance(alice, ethers.parseEther("1"));There is also changeTokenBalance for ERC-20 transfers.
await expect(
() => vault.connect(alice).withdraw()
).to.changeEtherBalance(alice, ethers.parseEther("1"));Reverts Without a Reason
Some failures have no message — for example, arithmetic underflow panics or plain revert(). Assert these generically:
await expect(token.transfer(bob.address, 999999))
.to.be.reverted;For panic codes specifically, use revertedWithPanic.
await expect(token.transfer(bob.address, 999999))
.to.be.reverted;Why This Matters
Testing reverts and events covers the negative and observable paths of your contract:
- Reverts prove your guards (access control, balance checks) actually block bad input.
- Events prove off-chain systems will receive the right notifications.
Skipping these leaves dangerous gaps in coverage.
Asserting State Did Not Change
After a revert, it is good practice to confirm state was untouched, since reverts roll back all changes:
await expect(
vault.connect(alice).withdraw()
).to.be.revertedWithCustomError(vault, "Unauthorized");
expect(await vault.balance()).to.equal(initial);This double-checks the guard truly protected the state.
await expect(
vault.connect(alice).withdraw()
).to.be.revertedWithCustomError(vault, "Unauthorized");
expect(await vault.balance()).to.equal(initial);Quick Check
Test your understanding of revert and event assertions.
Recap
You learned to assert behavior beyond return values.
revertedWithchecks require messages;revertedWithCustomErrorchecks custom errors.withArgsverifies error or event arguments precisely..to.emitconfirms events fired.changeEtherBalance/changeTokenBalanceassert net balance changes.- Use
.to.be.revertedfor failures without a reason string.
Часто задаваемые вопросы
Урок «Тестирование откатов и событий» бесплатный?
Да — полный текст урока «Тестирование откатов и событий» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 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 структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Тестирование откатов и событий»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Web3 & DApp Development Fundamentals?
Да. Каждый урок Web3 & DApp Development Fundamentals включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Написание тестов
- Тестирование откатов и событий
- Покрытие и отчёты о расходе газа
- Фикстуры