使您的测试更具可读性
在我以前的博客文章中,我写了关于使用JavaScript测试智能合约的文章。 在这一篇中,我想展示我在使测试更具可读性和优雅性的过程中选择的技术。
为此,我将使用在使用JavaScript测试智能合约中创建的代码作为参考。 请先阅读该博客文章。
继续我们离开的地方
为了美化测试代码,让我们使用一些方便的库。 请继续安装以下这些:
npm install --only = dev-保存
npm install --only = dev-保存chai-promise
npm install --only = dev-保存chai-bignumber
我们将添加这些chai库,以在测试中使用优雅的代码语法扩展chai。
转到/test
文件夹并创建一个helpers.js
文件。 将以下代码添加到该文件:
const BigNumber = web3.BigNumber
const应该= require('chai')
.use(需要('chai-promise')
.use(需要('chai-bignumber')(BigNumber))
。应该()
const EVMThrow ='无效的操作码'
module.exports = {应该,EVMThrow}
而已。
在我们的测试中应用
让我们用新的语法修改我们的第一个测试,以便有一个主意。 这是第一次测试的修改。
fundRaise.js
const FundRaise = artifacts.require('./ FundRaise.sol')
const {应该} = require('./ helpers')
合同(“ FundRaise”,函数([所有者,捐赠者]){
...
它(“具有所有者”,异步函数(){
const fundRaiseOwner =等待fundRaise.owner()
fundRaiseOwner.should.be.equal(所有者)
})
...
首先,我们需要来自helpers.js
文件,如下所示:
const {应该} = require('./ helpers')
然后,我们通过删除assert
语法来更改第一个测试,以使其更具可读性。
它(“具有所有者”,异步函数(){
const fundRaiseOwner =等待fundRaise.owner()
fundRaiseOwner.should.be.equal(所有者)
})
在这里,我们看到模式变为variable
+。 should
+ (expectation).
equal
+ equal
+ (expectation).
您可以在此处找到should
提供的api的整个范围。
将这种语法应用于fundRaise.js
的其余测试时,情况fundRaise.js
。
我很想知道您拥有/想出哪种优雅的解决方案来使用JS测试您的智能合约。
可以在以下网址找到此博客文章的代码https://github.com/gustavoguimaraes/smart-contract-testing-javascript-example-/tree/feature/beautifying-tests