0Pricing
Web3 & DApp Development Fundamentals · Leçon

Tester les annulations et événements

Vérifier le comportement

Tester les annulations et événements est une leçon Web3 & DApp Development Fundamentals gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Web3 & DApp Development Fundamentals, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Web3 & DApp Development Fundamentals comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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.

  • revertedWith checks require messages; revertedWithCustomError checks custom errors.
  • withArgs verifies error or event arguments precisely.
  • .to.emit confirms events fired.
  • changeEtherBalance / changeTokenBalance assert net balance changes.
  • Use .to.be.reverted for failures without a reason string.

Questions Fréquemment Posées

La leçon « Tester les annulations et événements » est-elle gratuite ?

Oui — le texte complet de « Tester les annulations et événements » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Web3 & DApp Development Fundamentals, passe à CoddyKit PRO. Le cours Web3 & DApp Development Fundamentals comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Tester les annulations et événements » ?

Vérifier le comportement Tu pratiques Web3 & DApp Development Fundamentals avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Web3 & DApp Development Fundamentals ?

Aucune expérience préalable n'est requise. Web3 & DApp Development Fundamentals sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.

Combien de temps prend la leçon « Tester les annulations et événements » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Web3 & DApp Development Fundamentals ?

Oui. Chaque leçon Web3 & DApp Development Fundamentals inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Écrire des tests
  2. Tester les annulations et événements
  3. Couverture et rapports de gas
  4. Fixtures
← Retour à Web3 & DApp Development Fundamentals