How to configure JEST to test a Typescript React or NodeJS

This is an opinionated guide that would illustrate how to configure Jest for testing NodeJS/React projects written in Typescript. It assumes Typescript is already installed. For new projects or projects without Typescript, needless, to say this guide can still be used upon completing the initial project setup to add React and or Typescript. There is a lot of guides out there already for adding Typescript to your project already.

1. Install Jest and friends

yarn add --dev jest ts-jest @types/jest
# or
npm i -D jest ts-jest @types/jest

  1. ts-jest is a TypeScript preprocessor for jest – it lets you use jest to test projects written in TypeScript.
  2. @types/jest types, because jest is written in JavaScript

2. Configure the preprocessor for Jest

Configure JEST to use ts-jest as the preprocessor. By using ts-jest to auto create a configuration file named jest.config.js with then jest preprocessor configs:

npx ts-jest config:init

Initial default generated output:

//jest.config.js
module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
};    

3. A complete opinionated configuration for Jest

My full customisations, settings self descriptive:

//jest.config.js
module.exports = {
  roots: ["<rootDir>/src"],
  preset: "ts-jest",
  testEnvironment: "node",
  coverageDirectory: "coverage",
  testPathIgnorePatterns: ["/node_modules"],
  verbose: true,
  // collectCoverage: true, <--Not needed because this would be applied/not by scripts in the package.json below
  coverageThreshold: {
    global: {
      branches: 90,
      functions: 95,
      lines: 95,
      statements: 90,
    },
  },
  collectCoverageFrom: ["**/*.{ts,tsx,js,jsx}", "!**/node_modules/**", "!**/vendor/**"],

  coveragePathIgnorePatterns: ["/node_modules"],
  coverageReporters: ["json", "lcov", "text", "clover"],
};

Note collectCoverage: true must be true or passed as a flag e.g. jest --coverage for coverage to be collected regardless of the content of the other coverage related settings.

For more on configuring jest see the official configuring Jest here

4. Configure the test scripts your package.json:

{
    "scripts": {
        "test": "jest"
    }
}

Or with advance/opinionated customisations. Self-explanatory naming:

{
    "scripts": {
        "test": "jest --coverage",
        "test:watch": "jest --coverage --watchAll",
        "test:nocoverage": "jest",
        "test:watch:nocoverage": "jest --watchAll"
    }
}

Congratulations if you got this far. This is a one off set-up, you would rip the benefits in days to come. Follow-on below to rest your Jest configuration for testing your Typescript React or NodeJs project.

5. Test it

To verify all is well

  1. Write a simple class, and a test for it see the JEST examples.
// sum.ts
const sum = (a: number, b: number) => {
  return a * b; // currently red, fixme: to go green (TDD).
};
export default sum;


// sum.test.ts
import sum from "./sum";

describe("test add function", () => {
  test("adds 1 + 2 to equal 3", () => {
    expect(sum(1, 2)).toBe(3); // should fail, fix function under test above.
  });
});

Then run the tests with the following, note the commands are from the script configured above

  1. yarn test to run the tests with coverage
  2. yarn test:watch to continuously run the tests. Highly recommended particular when doing TDD (Test Driven Development)
  3. yarn test:watch:nocoverage to continuously run the tests with no coverage, faster feedback.
  4. yarn view:coverage hosts the reports as a static website, note serve needs to be globally installed: yarn global add serve

Example out put when I run yarn test:

yarn test Example console output with failing test.
yarn test example console output with failing test.

Go on fix the test, you know you want to if you have not already done so. Here is what the output should look like once all your test(s) are passing:

yarn test Example console output with passing test.
yarn test example console output with passing test.

Thank you! Enjoy!

-MM

Leave a Reply