Reverts und Events testen
Verhalten überprüfen
Reverts und Events testen ist eine kostenlose Web3 & DApp Development Fundamentals-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Web3 & DApp Development Fundamentals-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Web3 & DApp Development Fundamentals-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Reverts und Events testen“ kostenlos?
Ja — der vollständige Text von „Reverts und Events testen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Web3 & DApp Development Fundamentals-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Web3 & DApp Development Fundamentals-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Reverts und Events testen“?
Verhalten überprüfen Du übst Web3 & DApp Development Fundamentals mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Web3 & DApp Development Fundamentals zu starten?
Keine Vorkenntnisse erforderlich. Web3 & DApp Development Fundamentals auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „Reverts und Events testen“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Web3 & DApp Development Fundamentals-Lektion Code schreiben und ausführen?
Ja. Jede Web3 & DApp Development Fundamentals-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Tests schreiben
- Reverts und Events testen
- Coverage- und Gas-Reports
- Fixtures