You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hardhat测试revertedWith/rejectWith报错:Invalid Chai property求助

解决Hardhat测试中revertedWith断言失效的问题

问题原因

你遇到的Invalid Chai property: revertedWith错误,是因为原生Chai不支持revertedWith这类区块链合约回滚断言,这个方法是Hardhat官方提供的Chai扩展插件@nomicfoundation/hardhat-chai-matchers特有的功能,必须正确安装并配置才能使用。

解决方案

1. 安装依赖插件

在项目根目录执行以下命令安装所需插件:

npm install --save-dev @nomicfoundation/hardhat-chai-matchers chai
# 或者使用yarn
yarn add --dev @nomicfoundation/hardhat-chai-matchers chai

2. 在Hardhat配置文件中注册插件

修改hardhat.config.js(或hardhat.config.ts),导入并启用这个插件:

// hardhat.config.js
require("@nomicfoundation/hardhat-chai-matchers");
require("@nomicfoundation/hardhat-toolbox"); // 若已使用toolbox,它内置了chai-matchers,可省略上方require

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.8.19", // 替换为你的合约编译版本
};

3. 确认测试代码中的expect来源

确保测试代码中使用的expect是Hardhat注入的扩展版本,不要手动引入原生Chai的expect。比如禁止写以下代码:

const { expect } = require("chai"); // 这会覆盖Hardhat带扩展功能的expect

Hardhat会自动在测试环境中注入带有区块链断言扩展的expect,直接使用即可。

验证修改后的测试代码

你的测试逻辑本身无问题,配置完成后可直接运行:

it("Should fail if sender does not have enough tokens", async function(){
    const initialOwnerBalance = await hardhatToken.balanceOf(owner.address);
    await expect(hardhatToken.connect(addr1).transfer(owner.address, 1)).to.be.revertedWith("Not enough tokens");

    expect((await hardhatToken.balanceOf(owner.address)).toString()).to.equal(initialOwnerBalance.toString());
})

额外说明

之前尝试的rejectWith报错,是因为原生Chai的rejectWith仅能处理普通Promise的拒绝,无法识别Solidity合约的回滚交易,必须使用Hardhat扩展的revertedWith来断言合约交易的回滚情况。

内容的提问来源于stack exchange,提问作者Brijesh Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:52:37