[Vite] Configure test environment in TypeScript-based React project

2024-04-22 hit count image

Let's see how to configure a test environment in a TypeScript-based React project created using Vite.

Outline

In this blog post, I will introduce how to configure a test environment in a TypeScript-based React project created using Vite. Let’s also see how to write test code using Jest and React Testing Library.

Blog series

This blog post is part of a series. Here is the list of Vite series.

Install Jest

Jest is a test framework created by Facebook and is the most commonly used test framework in React projects. With Jest, you can write and run test code for JavaScript.

To install Jest in a TypeScript-based React project created using Vite, run the following command.

npm i -D jest @types/jest ts-jest
# yarn add -D jest @types/jest ts-jest
  • jest: Install Jest.
  • @types/jest: Install the type definition file for Jest.
  • ts-jest: A package that supports running Jest using TypeScript.

Install Testing Libarary

React Testing Library is a library used to test React components. With React Testing Library, you can write tests to verify the rendering results of React components or trigger events.

To install React Testing Library in a TypeScript-based React project created using Vite, run the following command.

npm i -D jest-environment-jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event jest-svg-transformer identity-obj-proxy
# yarn add -D jest-environment-jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event jest-svg-transformer identity-obj-proxy
  • jest-environment-jsdom: A package that allows Jest to use the jsdom environment.
  • @testing-library/react: Install React Testing Library.
  • @testing-library/jest-dom: A package that allows Jest to use React Testing Library.
  • @testing-library/user-event: A package that triggers events used in React Testing Library.
  • jest-svg-transformer: A package that allows Jest to use SVG files.
  • identity-obj-proxy: A package that allows Jest to use CSS Module when using CSS Module.

Jest basic configuration

To test a TypeScript-based React project using Jest, you need to configure Jest. Run the following command to create a Jest configuration file in the root directory.

npx ts-jest config:init
# yarn ts-jest config:init

Then, you can see the jest.config.js file, which is the configuration file of Jest, created in the root directory. When you open the file, you can see the following code.

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

Vite-created projects use ES Modules as the default module system, so you need to change module.export (CommonJS module system) to export default (ES Modules system) as follows.

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

Also, React projects use CommonJS and ES modules differently, so there may be warnings when running tests. To prevent this, open the tsconfig.json file and set the esModuleInterop option as follows.

{
  ...
  "compilerOptions": {
    "esModuleInterop": true,
    ...
  },
  ...
}

Configure jest-environment-jsdom

Jest’s default test environment is set to node as follows.

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

However, React tests should be run in a DOM environment, so you need to set it to use jest-environment-jsdom as follows.

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  preset: 'ts-jest',
  testEnvironment: 'jest-environment-jsdom',
};

Configure React Testing Library

When testing React components with React Testing Library, you need to configure it to use Matchers for React components provided by React Testing Library.

To configure Matchers for Jest provided by React Testing Library, create a jest.setup.ts file in the root directory and import @testing-library/jest-dom as follows.

import '@testing-library/jest-dom';

And then open the jest.config.js file and add the setupFilesAfterEnv option as follows.

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
  setupFilesAfterEnv: ['./jest.setup.ts'],
};

To be able to use the Matchers types of React Testing Library in the test files of Jest, open the tsconfig.json file and add the types option as follows.

{
  ...
  "compilerOptions": {
    "esModuleInterop": true,
    "types": ["@testing-library/jest-dom"],
    ...
  },
  ...
}

Configure CSS and SVG files

To use CSS files and SVG files in Jest, you need to add the moduleNameMapper option to the jest.config.js file to make Jest use CSS files and SVG files.

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  preset: 'ts-jest',
  testEnvironment: 'jest-environment-jsdom',
  setupFilesAfterEnv: ['./jest.setup.ts'],
  moduleNameMapper: {
    '^.+\\.svg$': 'jest-svg-transformer',
    '\\.(css|less|scss)$': 'identity-obj-proxy',
  },
};

Execute Jest

Now you can test a TypeScript-based React project using Jest and React Testing Library. To run the test using Jest, open the package.json file and modify it as follows.

"scripts": {
  ...
  "test": "jest --watchAll",
  "test:ci": "jest --ci"
},

After modifying the package.json file, run the following command to run Jest.

npm run test
# yarn test

Then, you can see Jest running well as follows.

No tests found, exiting with code 0

Watch Usage
 › Press f to run only failed tests.
 › Press o to only run tests related to changed files.
 › Press p to filter by a filename regex pattern.
 › Press t to filter by a test name regex pattern.
 › Press q to quit watch mode.
 › Press Enter to trigger a test run.

Currently, we don’t have any test code written, so you can see the message No tests found being displayed.

Write test code

Now let’s see how to write test code using Jest and React Testing Library in a TypeScript-based React project. Create an App.test.tsx file in the src directory and modify it as follows.

import { render, screen } from '@testing-library/react';
import App from './App';

describe('<App />', () => {
  it('Rendered well', async () => {
    const { container } = render(<App />);

    expect(screen.getByAltText('Vite logo')).toBeInTheDocument();
    expect(screen.getByAltText('React logo')).toBeInTheDocument();
    expect(screen.getByText('Vite + React')).toBeInTheDocument();

    expect(container).toMatchSnapshot();
  });
});

This test code uses Jest and React Testing Library to check if the Vite logo, React logo, and Vite + React text are rendered well.

To run the test you created, run the following command in the terminal to run the test.

npm run test
# yarn test

Then, you can see that the test runs well as follows.

  PASS  src/App.test.tsx
  <App />
    ✓ Rendered well (20 ms)

 › 1 snapshot written.
Snapshot Summary
 › 1 snapshot written from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 written, 1 total
Time:        1.749 s, estimated 2 s
Ran all test suites.

Watch Usage
 › Press f to run only failed tests.
 › Press o to only run tests related to changed files.
 › Press p to filter by a filename regex pattern.
 › Press t to filter by a test name regex pattern.
 › Press q to quit watch mode.
 › Press Enter to trigger a test run.

Also, we’ve written a snapshot test using toMatchSnapshot, so you can see that a snapshot file is created in the __snapshots__ directory.

Completed

Done! We’ve seen how to configure a test environment in a TypeScript-based React project created using Vite. Now you can write test code using Jest and React Testing Library to develop a safe and stable React project.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts