Boost your Javascript test lifecycle with uvu

Boost your Javascript test lifecycle with uvu

You might relate to this scenario: hundreds of tests written, you change something in the code and wait the test suite to rerun and seconds seems like hours...well, today I want to recommend you a new/lightweight/fast library: uvu

Hands-on

npm install --save-dev uvu
# this one is just for this test
npm install node-fetch

Write a basic test in a tests folder:

const { test } = require('uvu');
// the assert lib is optional, you might use Node's assert module,
// Chai, whatever!
const assert = require('uvu/assert');
const fetch = require('node-fetch');
const expected_response =  {
    userId: 1,
    id: 1,
    title: "delectus aut autem",
    completed: false
};

test('validate expected response', () => {
    assert.is(1, expected_response.id);
    assert.ok(expected_response.userId > 0);
    assert.is.not(true, expected_response.completed);
});

test('async tests', async () => {
    // look ma! Async/await tests!
    const url = 'https://jsonplaceholder.typicode.com/todos/1';
    const response = await fetch(url);
    assert.equal(await response.json(), expected_response);
});

// I must say I like the explicitness, the test file becomes self-contained
test.run();

Now let's add a npm test task to run every test in the tests folder:

// package.json
{
    "scripts": {
        "test": "uvu tests"
    }
}

Now run npm test to see a beautiful and concise output for your test suite!

Bonus: Code Coverage

Install c8 and watchlist to add coverage to your workflow:

npm install c8 watchlist --save-dev

And add these tasks:

// package.json
{
    "scripts": {
        "test": "c8 node tests/*.js",
        "dev": "watchlist src tests -- c8 node tests/*.js"
    }
}

Now every time you change your code, the coverage should be automatically generated inside the dist folder. If you are used to Mocha or Ava like me, you will be surprised by the performance!

It's a matter of asking yourself if the minimalistic API surface of uvu is enough for your project, as I like to keep my code close to the "metal" I'm more than satisfied!