Unit test with ES2020

Photo by Birmingham Museums Trust on Unsplash

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

Result

1 test passed

Happy ES2020!

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Expence Tracker Design Vue

Task 7.2 — Write a blog explaining the usecase of javascript in any of your favorite Industry

How To Find And Hire JavaScript Developers?

Rest APIs and Node.js

Intro to Animations in React Native

Optimizing event handler of input without affecting browser and application performance in React.js

Ionic & Firebase Image Upload Example

Best Coding Practices — React Native Edition 2022

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
Anthony Ng

Anthony Ng

Software Engineer

More from Medium

CS373 Spring 2022 Week 9: Vibhuti Sharma

Introduction to Git and GitHub

Sliding Window Example - Longest Substring without Repeating Characters

Connect SAP Commerce to SAP BTP kyma runtime