Using Jest with TypeScript

Pro egghead lesson on Jest / TypeScript

No testing solution out there is perfect. That said, jest is an excellent unit testing option which provides great TypeScript support.

Note: We assume you start off with a simple node package.json setup. Also all TypeScript files should be in a src folder which is always recommended (even without Jest) for a clean project setup.

Step 1: Install

Install the following using npm:

  1. npm i jest @types/jest ts-jest -D

Explanation:

  • Install jest framwork (jest)
  • Install the types for jest (@types/jest)
  • Install the TypeScript preprocessor for jest (ts-jest) which allows jest to transpile TypeScript on the fly and have source-map support built in.
  • Save all of these to your dev dependencies (testing is almost always a npm dev-dependency)

Step 2: Configure Jest

Add the following jest.config.js file to the root of your project:

  1. module.exports = {
  2. "roots": [
  3. "<rootDir>/src"
  4. ],
  5. "transform": {
  6. "^.+\\.tsx?$": "ts-jest"
  7. },
  8. "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  9. "moduleFileExtensions": [
  10. "ts",
  11. "tsx",
  12. "js",
  13. "jsx",
  14. "json",
  15. "node"
  16. ],
  17. }

Explanation:

  • We always recommend having all TypeScript files in a src folder in your project. We assume this is true and specify this using roots option.
  • The transform config just tells jest to use ts-jest for ts / tsx files.
  • The testRegex tells Jest to look for tests in any __tests__ folder AND also any files anywhere that use the (.test|.spec).(ts|tsx) extension e.g. asdf.test.tsx etc.
  • The moduleFileExtensions tells jest to recognize our file extensions. This is needed as we add ts/tsx into the defaults (js|jsx|json|node).

Step 3: Run tests

Run npx jest from your project root and jest will execute any tests you have.

Optional: Add script target for npm scripts

Add package.json:

  1. {
  2. "test": "jest"
  3. }
  • This allows you to run the tests with a simple npm t.
  • And even in watch mode with npm t -- --watch.

Optional: Run jest in watch mode

  • npx jest -w

Example

  • For a file foo.ts:

    1. export const sum
    2. = (...a: number[]) =>
    3. a.reduce((acc, val) => acc + val, 0);
  • A simple foo.test.ts:

  1. import { sum } from '../';
  2. test('basic', () => {
  3. expect(sum()).toBe(0);
  4. });
  5. test('basic again', () => {
  6. expect(sum(1, 2)).toBe(3);
  7. });

Notes:

  • Jest provides the global test function.
  • Jest comes prebuilt with assertions in the form of the global expect.

Example async

Jest has built-in async/await support. e.g.

  1. test('basic',async () => {
  2. expect(sum()).toBe(0);
  3. });
  4. test('basic again', async () => {
  5. expect(sum(1, 2)).toBe(3);
  6. }, 1000 /* optional timeout */);

Example enzyme

Pro egghead lesson on Enzyme / Jest / TypeScript

Enzyme allows you to test react components with dom support. There are three steps to setting up enzyme:

  1. Install enzyme, types for enzyme, a better snapshot serializer for enzyme, enzyme-adapter-react for your react version npm i enzyme @types/enzyme enzyme-to-json enzyme-adapter-react-16 -D
  2. Add "snapshotSerializers" and "setupTestFrameworkScriptFile" to your jest.config.js:
  1. module.exports = {
  2. // OTHER PORTIONS AS MENTIONED BEFORE
  3. // Setup Enzyme
  4. "snapshotSerializers": ["enzyme-to-json/serializer"],
  5. "setupTestFrameworkScriptFile": "<rootDir>/src/setupEnzyme.ts",
  6. }
  1. Create src/setupEnzyme.ts file.
  1. import { configure } from 'enzyme';
  2. import * as EnzymeAdapter from 'enzyme-adapter-react-16';
  3. configure({ adapter: new EnzymeAdapter() });

Now here is an example react component and test:

  • checkboxWithLabel.tsx:
  1. import * as React from 'react';
  2. export class CheckboxWithLabel extends React.Component<{
  3. labelOn: string,
  4. labelOff: string
  5. }, {
  6. isChecked: boolean
  7. }> {
  8. constructor(props) {
  9. super(props);
  10. this.state = { isChecked: false };
  11. }
  12. onChange = () => {
  13. this.setState({ isChecked: !this.state.isChecked });
  14. }
  15. render() {
  16. return (
  17. <label>
  18. <input
  19. type="checkbox"
  20. checked={this.state.isChecked}
  21. onChange={this.onChange}
  22. />
  23. {this.state.isChecked ? this.props.labelOn : this.props.labelOff}
  24. </label>
  25. );
  26. }
  27. }
  • checkboxWithLabel.test.tsx:
  1. import * as React from 'react';
  2. import { shallow } from 'enzyme';
  3. import { CheckboxWithLabel } from './checkboxWithLabel';
  4. test('CheckboxWithLabel changes the text after click', () => {
  5. const checkbox = shallow(<CheckboxWithLabel labelOn="On" labelOff="Off" />);
  6. // Interacton demo
  7. expect(checkbox.text()).toEqual('Off');
  8. checkbox.find('input').simulate('change');
  9. expect(checkbox.text()).toEqual('On');
  10. // Snapshot demo
  11. expect(shallow).toMatchSnapshot();
  12. });

Reasons why we like jest

For details on these features see jest website

  • Built-in assertion library.
  • Great TypeScript support.
  • Very reliable test watcher.
  • Snapshot testing.
  • Built-in coverage reports.
  • Built-in async/await support.