Beautifying Your Smart Contract Tests With JavaScript

Make your tests more readable

Photo by Kelly Sikkema

In my previous blog post I wrote about testing smart contracts with JavaScript. In this one, I would like to show techniques I picked along the way that makes tests more readable and elegant.

For this, I am going to use the code created in Testing Your Smart Contract With JavaScript as reference. Please read that blog post first.

Carrying On Where We Left Off

To beautify out test code, let’s use some handy libraries. Please go ahead and install these:

npm install --only=dev --save chai
npm install --only=dev --save chai-as-promised
npm install --only=dev --save chai-bignumber

We are adding these chai libraries to extend chai with elegant code syntax in our tests.

Go to the/test folder and create a helpers.js file. Add the following code to this file:

const BigNumber = web3.BigNumberconst should = require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bignumber')(BigNumber))
.should()
const EVMThrow = 'invalid opcode'module.exports = { should, EVMThrow }

That’s it.

Applying in our tests

Let’s modify our first test with the new syntax so we have an idea. Here is the modification on the first test.

fundRaise.js

const FundRaise = artifacts.require('./FundRaise.sol')
const { should } = require('./helpers')
contract('FundRaise', function ([owner, donor]) {... it('has an owner', async function () {
const fundRaiseOwner = await fundRaise.owner()
fundRaiseOwner.should.be.equal(owner)
})
...

First we require should from the helpers.js file as such:

const { should } = require('./helpers')

Then we change the first test by removing the assert syntax to the more readable should one.

it('has an owner', async function () {
const fundRaiseOwner = await fundRaise.owner()
fundRaiseOwner.should.be.equal(owner)
})

Here we see that the pattern becomes variable + .should + .be+ equal + (expectation). You are able to find the whole range of api that should provides here.

This is what it looks like when applying this syntax to the rest of the tests withinfundRaise.js .

I am curious to see what kind of elegant solution you have/ come up with testing your smart contracts with JS.

The code for this blog post is found here https://github.com/gustavoguimaraes/smart-contract-testing-javascript-example-/tree/feature/beautifying-tests

Gustavo (Gus) Guimaraes

Written by

A curious mind, joie de vivre practitioner

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade