How to setup Node.js testing with ava

May 26, 2022

This tutorial will explain from the project setup. To skip the setup you can go to installation

Setup

Create new node.js project

$ npm init --y

Create a simple function to test

// add.js
/**
 * Add two numbers
 * @param {number} a a number
 * @param {number} b a number
 * @returns a + b
 */
exports.add = (a, b) => a + b;

You can test that function with console.log

Installation

Install ava to the project

$ npm i -D ava

Add test script that runs the ava binary

// package.json
{
  // ...
  "scripts": {
    // ...
    "test": "ava"
  }
}

Testing

Create a test file to test the add function

// add.test.js
const test = require('ava');
const { add } = require('./add');

test('should correctly add 1 and 1', t => {
  t.is(add(1, 1), 2);
});

Then you can run the test script

$ npm test

Tips

To get types/intellisense in vscode, modify how to import ava

- const test = require("ava");
+ const { default: test } = require("ava");

References