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:

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 should = require('chai')
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.


contract('FundRaise', function ([owner, donor]) {...    it('has an owner', async function () {
const fundRaiseOwner = await fundRaise.owner()

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

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

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



A curious mind, joie de vivre practitioner

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store