Solidity:使用 waffle + chai 测试恢复的断言不起作用
Posted
技术标签:
【中文标题】Solidity:使用 waffle + chai 测试恢复的断言不起作用【英文标题】:Solidity: Testing reverted assertions with waffle + chai doesn't work 【发布时间】:2021-12-14 20:28:51 【问题描述】:我正在测试一个 ERC721 代币的智能合约,它继承自 OpenZeppelin,使用 waffle 和 chai 和 NodeJS v14.18.0,但 chai 的还原断言似乎没有按预期运行。
依赖关系:
"devDependencies":
"@nomiclabs/hardhat-ethers": "^2.0.1",
"@nomiclabs/hardhat-etherscan": "^2.1.0",
"@nomiclabs/hardhat-waffle": "^2.0.1",
"@typechain/ethers-v5": "^5.0.0",
"@types/chai": "^4.2.14",
"@types/mocha": "^8.2.0",
"@types/node": "^14.14.14",
"chai": "^4.2.0",
"dotenv": "^8.2.0",
"ethereum-waffle": "^3.2.1",
"ethers": "^5.0.24",
"hardhat": "^2.0.5",
"hardhat-typechain": "^0.3.4",
"ts-generator": "^0.1.1",
"ts-node": "^9.1.1",
"typechain": "^4.0.1",
"typescript": "^4.1.3"
,
示例代码:
let genesisTokenHolders: Array<string>;
beforeEach(async () =>
genesisTokenHolders = new Array(230).fill('0x0000000000000000000000000000000000000000')
genesisTokenHolders[1] = addr1.address;
genesisTokenHolders[2] = addr2.address;
)
describe('airdrop genesis tokens', async () =>
it('should fail when non-owner calls the function', async () =>
let addGenesisHoldersTx = await myToken.addGenesisTokenHolderAddresses(genesisTokenHolders)
await addGenesisHoldersTx.wait();
await expect(await myToken.connect(addr1).airdropTokensToGenesisHolders(1, 2)).to.be.revertedWith("Ownable: caller is not the owner");
)
it('should succeed when called by the owner', async () =>
let addGenesisHoldersTx = await myToken.addGenesisTokenHolderAddresses(genesisTokenHolders)
await addGenesisHoldersTx.wait();
let airdropTx = await myToken.connect(deployer).airdropTokensToGenesisHolders(1,2);
await airdropTx.wait();
// addr1 should own tokenID 1, addr2 should own tokenId 2
await expect(await myToken.ownerOf(1)).to.hexEqual(addr1.address)
await expect(await myToken.ownerOf(2)).to.hexEqual(addr2.address)
await expect(await myToken.ownerOf(1000)).to.be.reverted;
)
);
尽管使用了.to.be.revertedWith()
和.to.be.reverted
,测试套件仍然抛出错误:
airdrop genesis tokens
should fail when non-owner calls the function:
Error: VM Exception while processing transaction: revert Ownable: caller is not the owner
airdrop genesis tokens
should succeed when called by the owner:
Error: VM Exception while processing transaction: revert ERC721: owner query for nonexistent token
预期结果:测试应该通过。
【问题讨论】:
【参考方案1】:不要等待承诺在 expect
内得到解决
更改自:
await expect(await myToken.ownerOf(1000)).to.be.reverted;
收件人:
await expect(myToken.ownerOf(1000)).to.be.reverted;
【讨论】:
以上是关于Solidity:使用 waffle + chai 测试恢复的断言不起作用的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 waffle 和 ethers.js 测试应付/外部方法
将 Waffle Spring Security XML 配置迁移到 Spring Boot
将 Tomcat 上的 Spring Security 和 Waffle 与角色检查集成