0Pricing
Web3 & DApp Development Fundamentals · 课时

测试回滚与事件

断言行为

测试回滚与事件 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.

  • 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.

常见问题解答

「测试回滚与事件」课时是免费的吗?

是的 — 「测试回滚与事件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

「测试回滚与事件」这节课中我会学到什么?

断言行为 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「测试回滚与事件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 编写测试
  2. 测试回滚与事件
  3. 覆盖率与 Gas 报告
  4. 测试夹具
← 返回 Web3 & DApp Development Fundamentals