如何直接使用Hardhat/Chai测试Solidity库



我正在尝试直接使用硬帽和chaï测试一个Solidity库。这是一个我想测试的库示例:

library LibTest {
function testFunc() public view returns(bool) {
return true;
}
}

,这就是我要测试它的方法。

beforeEach(async () => {
const LibTest = await ethers.getContractFactory("LibTest");
const libTest = await LibTest.deploy();
await libTest.deployed();
})
describe('Testing test()', function () {
it("is working testFunc ?", async function () {
console.log(await libTest.testFunc());
})
})

但是我有错误信息:

ReferenceError: libTest is not defined

我尽我所能阅读Chai文档和Hardhat文档,但无法找到任何解决方案

我会说使用fixture,也使用waffle,并部署一次库合同并保存合同的snapshot:

const {loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const {expect} = require('chai');
const {ethers, waffle} = require('hardhat');
const {deployContract} = waffle;
const LibArtifact = require('../artifacts/contracts/lib.sol/LibTest.json');
describe("Lib tests", function () {
// We define a fixture to reuse the same setup in every test.
// We use loadFixture to run this setup once, snapshot that state,
// and reset Hardhat Network to that snapshopt in every test.
async function deployOnceFixture() {
const [owner, ...otherAccounts] = await ethers.getSigners();
lib = (await deployContract(owner, LibArtifact));
return { lib, owner, otherAccounts };
}
describe("Testing test()", function () {
it("s working testFunc ?", async function () {
const { lib } = await loadFixture(deployOnceFixture); 
expect(await lib.testFunc()).to.be.true;
});
});
});

添加waffle插件的说明:Hardhat-waffle基本上,您需要安装这些库:

npm install --save-dev @nomiclabs/hardhat-waffle 'ethereum-waffle@^3.0.0' @nomiclabs/hardhat-ethers 'ethers@^5.0.0'

然后将hardhat-waffle导入hardhat-config.js文件:

require("@nomiclabs/hardhat-waffle");

另外,请注意我将test文件放在test目录中,因此我需要返回一个文件夹来查找通过运行npx hardhat compile生成的artifacts。为方便起见,我将解决方案放在Github repo中:https://github.com/Tahlil/run-solidity-lib

我发现最好的方法是创建一个LibTest。调用和测试Lib本身的sol契约。只是在JS/TS中运行抽象测试来调用LibTest合约,连接Lib。

const Lib = await ethers.getContractFactory("Lib");
const lib = await Lib.deploy();
const LibTest = await ethers.getContractFactory("LibTest", {
libraries: {
Lib: lib.address,
},
});
const libTest = await LibTest.deploy();
/// later: console.log(await libTest.testLibFunc());

LibTest.sol:

import "./Lib.sol";
library LibTest {
function testLibFunc() public view returns(bool) {
bool response = Lib.testFunc();
return response;
}
}

你能找到更好的方法吗?

相关内容

  • 没有找到相关文章

最新更新