DEV Community

Avelyn Hyunjeong Choi
Avelyn Hyunjeong Choi

Posted on

Testing Typescript with Jest

Testing framework - Jest
I used Jest for this because I've used it before, but I can't remember exactly how to use it. So I needed a reminder and had to figure out how to use it with TypeScript, as I had only used it for JavaScript.

What is Jest?
It is a testing framework to make sure your code does what it's supposed to do.

Set up for Typescript
1.Installation
install Jest
npm install --save-dev jest
generate a basic config file
npm init jest@latest
install @types/jest as a development dependency
npm install --save-dev @types/jest

2.Automatically generated config file for Jest

// jest.config.js

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
Enter fullscreen mode Exit fullscreen mode

3.Update .eslintrc.cjs config file so that ESLint knows we are using Jest

// .eslintrc.cjs

module.exports = {
  extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  root: true,
  env: {
    browser: true,
    es6: true,
    jest: true,
    node: true,
  },
  overrides: [
    {
      files: ['**/*.tsx'],
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

4.Add some npm scripts to your package.json to run the unit tests.

  "scripts": {
    ...
    "test:watch": "jest -c jest.config.js --runInBand --watch --",
    "test": "jest -c jest.config.js --runInBand --",
    "coverage": "jest -c jest.config.js --runInBand --coverage"
  },
Enter fullscreen mode Exit fullscreen mode

5.Run the test
$ npm run test

Learning moment while writing the test case
While I was testing the fileHandler method, I needed to use a mock to be able to test whether this function logs the correct message, as it does not return anything. It was my first time using a mock for a unit test.

Here are the steps I used:
1) mock of console.log() was created using the jest.spyOn() function, which allows us to capture calls to console.log().
2) called the fileHandler() method.
3) made an assertion about consoleLogMock to check whether console.log() was called with the specified argument.
4) restored the original console.log() function.

  test('fileHandler() should be able to handle text file', () => {
    const consoleLogMock = jest.spyOn(console, 'log').mockImplementation(() => {});

    fileHandler(...);

    expect(consoleLogMock).toHaveBeenCalledWith('test1.html is created successfully!');
    consoleLogMock.mockRestore();
  });
Enter fullscreen mode Exit fullscreen mode

Learning moment in general
It was definitely different to use Jest for JavaScript. As mentioned above, I have used Jest before for JavaScript. It was a lot different in terms of setup. For example, the same file name, jest.config.js, was used, but the content inside the file was completely different. In JavaScript, this config file loads the env.jest test environment variables, while in TypeScript, it has simpler code.

Details in code: ec2f6c9

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay