Unit test with ES2020

ES2020 has released in June. Developers are fascinated by the new features like nullish coalescing, optional chaining, and Promise.allSettled. To experiment with it in the production pipeline, the unit test suite is likely the first thing developers need to deal with. I have been using TDD approach with Mocha and Chai for a few years. However, it is tricky to use Mocha with ES2020.

After a few hassles with ESM and Mocha, I decided to give Ava a try. Ava.js offers a more natural and less hacky setup, and let’s see how straightforward it is.

ES2020 Setup

Initialise a node project and setup ES2020 with the below Babel libraries.

$ yarn init -y$ yarn add @babel/cli @babel/core @babel/node @babel/preset-env

Create babel property file .babelrc with the below content.

{  "presets": ["@babel/preset-env"]}

Setup Ava and ESM

Install ESM

$ yarn add esm

Install Ava

$ yarn add -D ava

Bind Ava and ESM in package.json

"ava": {  "require": [ "esm" ]}

Unit Test

Now let’s create a simple function sum

export default function sum(a, b) {  return a + b;};

And a basic unit test sum.test.js.

import test from 'ava';import sum from './sum';
test('1 + 1 = 2', t => {
t.is(sum(1, 1), 2);});

Run the test

$ npx ava


1 test passed

Happy ES2020!



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