リバートとイベントのテスト
動作をアサートします
「リバートとイベントのテスト」はCoddyKit上の無料Web3 & DApp Development Fundamentalsレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これは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時間対応のAIチューター)、Web3 & DApp Development Fundamentalsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Web3 & DApp Development Fundamentalsコースには全4レッスンが含まれています。
「リバートとイベントのテスト」で何を学びますか?
動作をアサートします ブラウザで直接実行するハンズオンコードでWeb3 & DApp Development Fundamentalsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Web3 & DApp Development Fundamentalsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのWeb3 & DApp Development Fundamentalsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「リバートとイベントのテスト」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このWeb3 & DApp Development Fundamentalsレッスンでコードを書いて実行できますか?
はい。すべてのWeb3 & DApp Development Fundamentalsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- テストの作成
- リバートとイベントのテスト
- カバレッジとGasレポート
- フィクスチャ