Testing application logic is critical part of the development life cycle if you wish to have easily maintainable and reliable code. Unit testing is one part of the testing formula, that is easy to implement, promotes good coding practices and gives peace of mind when refactoring. At Simply Anvil we make use of Jest since it is easy to get up and running with the framework, it has a large, growing comunity and it has a lot of features right out of the box.

Setting up jest in your Node.js project

Install jest libraries

npm install --save-dev jest @types/jest ts-jest

Add jest.config.ts to your root directory

module.exports = {
  testEnvironment: 'node',
  moduleFileExtensions: [
    'ts',
    'tsx',
    'js'
  ],
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest'
  },
  testMatch: [
    '**/?(*.)(spec|test).(ts|tsx|js)?(x)'
  ]
};

Add scripts for easy testing

Update package.json

"scripts": {
  "test": "jest --watch",
  "test:ci": "jest --ci --colors --coverage"
}

Running tests

In your terminal, in the project directory execute 1 of the following commands. (Jest will throw an error that no tests are found if you execute these commands at this stage)

  • Test while developing

npm run test

Runs tests in watch mode. This only runs tests for files that have changed since the last commit.

  • Test with coverage

npm run test:ci

This will run all tests and additionally create a coverage directory with the coverage report in your project root directory.

--watch issue with subrepositories

When working with git subrepositories, change detection may not work properly and it may be necessary to use jest’s watch all flag to ensure all tests are run.

Update package.json

"scripts": {
  ...
  "test:all": "jest --watchAll",
  ...
}
  • Test all while developing

npm run test:all

Runs all tests in watch mode on every change. Use this only npm run test is not working as expected

Finally start adding test files

Use format /name.spec.ts/

describe('some module/library/class', () => {
  it('should (not) do something', () => {
    // test expectation
    expect(1++).toBe(2);
  })
})

example

// merchant.spec.ts
import { getMerchant } from './merchant.ts'

describe('Function getMerchant', () => {
  it('should return the merchant matching merchant id', () => {
    const expectedResponse = {name: 'Distribution partner'};

    expect(getMerchant('73GiDd3mai3')).toEqual(expectedResponse);
  });
});

Conclusion

This article focused only on getting started with Jest in your Node.js project. Next we will cover test/spec files in more depth, as well as mocks, stubs and spies and when to use them.