如何在Hardhat(TypeScript)项目中正确导入@nomicfoundation/hardhat-chai-matchers?
Hardhat-Chai-Matchers 未生效:BigNumber与普通数字断言失败问题
我按照官方指引,在hardhat.config.ts中添加了以下导入:
import '@nomicfoundation/hardhat-chai-matchers';
测试代码中写了这样的断言:
expect(maxCount).to.equal(64);
其中maxCount是ethers.js的BigNumber类型,64是常规JavaScript/TypeScript数字,但运行后出现错误:
AssertionError: expected [ BigNumber { value: "64" } ] to equal 64
这说明hardhat-chai-matchers并未生效——它本应自动处理BigNumber和普通数字的断言转换。我怀疑是导入方式有误,想知道TypeScript项目下正确的导入方式是什么?
官方文档的使用章节给出的是CommonJS的require写法:
require("@nomicfoundation/hardhat-chai-matchers");
我的项目(包括hardhat配置)使用TypeScript,所以改用了import写法。
补充信息
开发依赖(package.json)
"devDependencies": { "@nomicfoundation/hardhat-chai-matchers": "1.0.6", "@nomicfoundation/hardhat-toolbox": "2.0.2", "@types/chai": "4.3.4", "@types/fs-extra": "11.0.1", "@types/mocha": "10.0.1", "@types/node": "18.14.6", "fs-extra": "11.1.0", "hardhat": "2.13.0", "ts-node": "10.9.1", "typescript": "4.9.5" }
运行环境版本
$ node -v v16.13.1 $ npm -v 8.1.2
调试信息
我手动修改了node_modules/@nomicfoundation/hardhat-chai-matchers/src/internal/bigNumber.ts,添加了console.log语句:
function overwriteBigNumberFunction( functionName: Methods, readableName: string, readableNegativeName: string, _super: (...args: any[]) => any, chaiUtils: Chai.ChaiUtils ) { console.log('hh chai matcher overwriteBigNumberFunction'); /* ... */ }
以及:
} else if (isBigNumber(expectedFlag) || isBigNumber(actualArg)) { console.log('hh chai matcher bignit'); /* ... */ }
之后运行npx hardhat console,未看到上述日志输出,进一步确认导入可能存在问题。
内容的提问来源于stack exchange,提问作者bguiz
相关产品推荐
相关产品推荐

