Testing JavaScript/TypeScript Snippets with Jest

January 18th 2019 Unit Testing JavaScript TypeScript

I often need to quickly test some JavaScript or TypeScript code, be it for a blog post or otherwise. Recently, I started using Jest for that because it's so simple to set up.

For basic JavaScript code, it's enough to install the npm package:

npm init
npm install --save-dev jest

During the npm init call, you should set jest as the test command. This can then be used to run the test command:

npm test

The files with the .test.js extension will automatically be picked up as test suites. The methods and matchers you can use to define tests are well documented:

const multiply = require('./sample');

test('multiplies two numbers', () => {
    expect(multiply(2, 3)).toBe(6);
});

CommonJS modules are supported out-of-the-box, allowing you to put the code under test into separate .js files:

function multiply(a, b) {
    return a * b;
}

module.exports = multiply;

I tend to write more TypeScript than JavaScript code. Although Jest doesn't have built-in support for it, it's almost just as easy to use with the help of ts-jest:

npm init
npm install --save-dev jest typescript ts-jest @types/jest
npx ts-jest config:init

The last command in the snippet above will create a jest.config.js file configured for the ts-jest preprocessor. Now, the tests can be in the files with .test.ts extension:

import { multiply } from "./sample";

test('multiplies two numbers', () => {
    expect(multiply(2, 3)).toBe(6);
});

This configuration is fully preconfigured for ECMAScript 6 modules which you can use put the code under test into a different .ts file:

export function multiply(a: number, b: number): number {
    return a * b;
}

Trying to use other ECMAScript 6+ features might result in an error:

test('supports ECMAScript 6 feature', () => {
    const orig = {
        prop: 'value'
    };
    const copy = Object.assign({}, orig);

    expect(copy).toEqual(orig);
});

The test above will fail to compile with the following error:

Property 'assign' does not exist on type 'ObjectConstructor'.

To fix this, the TypeScript compiler needs to be properly configured. Thanks to ts-jest, Jest will automatically pick up the tsconfig.json file if it's present in the root folder. The following is enough to fix the above error:

{
    "compilerOptions": {
        // ...
        "target": "es5",
        "lib": ["es2015", "es2017", "dom"]
        // ...
    }
}

That should be enough to test most TypeScript code. Of course, you can always add other compiler options to tailor the compiler behavior to your liking.

And if you're using VS Code, you might want to install the Jest extension for an even better experience.

Copyright
Creative Commons License