DEV Community

Cover image for Installing Jest for Testing in Your Vite-React TypeScript Project. A Step-by-Step Guide.
Hannah Ejimofor
Hannah Ejimofor

Posted on • Updated on

Installing Jest for Testing in Your Vite-React TypeScript Project. A Step-by-Step Guide.

Introduction

Application testing is an important aspect of web development. It helps eliminate bugs before these applications are pushed out to the users. Testing applications also helps in maintaining and refactoring code, especially in collaborative projects where a developer makes a change that is out of context thereby promoting good collaboration among teammates. It also ensures the code quality and correctness.
The aim of the article is to show how unit testing is done in a react-vite app with Jest. From the setup, down to the implementation.

Jest

To know more about Jest as a testing framework, visit jest website

Prerequisite

To get started, we will need the following:

  • PC and a text editor. (Just kidding, of course, we already have that)
  • npm or yarn installed

We will start by creating a react app with Vite then we proceed to set up Jest for the testing and try out some tests on the react components.

Use Case

Step 1: Creating the react app with Vite

Open the terminal in your text editor (For the project, we will be making use of the VSCode) and proceed to create the react app using the command below:
npm create vite@latest

Follow the wizard and select the desired options

Vite create react app
From the above, you'd see we have selected React and Typescript, and we called the project "mini-app-testing" so we will be building with Typescript.

  • Now run the following commands to get started and install the needed packages, step by step.

cd mini-app-testing - to navigate to the project directory.

npm install - to install the packages. (You can also use yarn but we started with npm so we stick with it).

npm run dev - to start the project.

If you have done the above correctly, you should have something like this
On your VSCode
App created and installation completed

On your browser
The live server

Step 2: Setting up Jest

Before we dive into the process, note that Vite has certain limitations with Jest which makes setting up Jest in a Vite application to seem a bit complicated.
Follow the process below to get started

  • npm install jest --save-dev
  • npm install @testing-library/react --save-dev
  • npm install ts-jest @types/jest --save-dev
  • In the package.json, add "test": jest to the script
// package.json

{
  "name": "mini-app-testing",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "test": "jest"
  },
Enter fullscreen mode Exit fullscreen mode
  • run npm run test and you receive a message saying no test found as seen below.

No test feedback on terminal

  • So to fix the above, In the src folder, we create a folder called __ tests __ and add the test file: src/__ tests __/App.spec.tsx.

Test file structure

  • Add a simple test in the test file: App.test.tsx
// src/__ tests __/App.test.tsx

test('demo', () => {
  expect(true).toBe(true)
})

Enter fullscreen mode Exit fullscreen mode
  • Run the npm run test again. Voila!!! our first test passed

Successful test run

Step 3: Testing the components

  • To test the components, we import the App.tsx into the App.test.tsx and run a simple truthy test on the App component.
// src/__ tests __/App.test.tsx

import { render } from "@testing-library/react"
import App from "../App"

test('demo', () => {
    expect(true).toBe(true)
})

test("Renders the main page", () => {
    render(<App />)
    expect(true).toBeTruthy()
})

Enter fullscreen mode Exit fullscreen mode
  • Let test again, run npm run test. But it will fail due to missing dependencies and configurations as seen below. So it has to be configured to be able to import and read imported components.

Error message

  • Run npm install ts-node @testing-library/jest-dom --save-dev
  • Run npm install jest-environment-jsdom
  • Run npm install identity-obj-proxy --save-dev

  • In your root directory, create a jest.config.ts file and add the following to it

// jest.config.ts

export default {
    preset: 'ts-jest',
    testEnvironment: 'jest-environment-jsdom',
    transform: {
        "^.+\\.tsx?$": "ts-jest" 
    // process `*.tsx` files with `ts-jest`
    },
    moduleNameMapper: {
        '\\.(gif|ttf|eot|svg|png)$': '<rootDir>/test/__ mocks __/fileMock.js',
    },
}
Enter fullscreen mode Exit fullscreen mode
  • In the src folder, create a test folder, then create a __ mocks __ folder in the test folder and add a fileMock.js file: src/test/__ mocks __/fileMock.js and add the following content:
// src/test/__ mocks __/fileMock.js

module.exports = {
    __esModule: true,
    default: 'test-file-stub',
};
Enter fullscreen mode Exit fullscreen mode
  • In the App.test.tsx, import @testing-library/jest-dom
// src/__ tests __/App.test.tsx

import '@testing-library/jest-dom'
import { render } from "@testing-library/react"
import App from "../App"

test('demo', () => {
    expect(true).toBe(true)
})

test("Renders the main page", () => {
    render(<App />)
    expect(true).toBeTruthy()
})
Enter fullscreen mode Exit fullscreen mode
  • Then run the npm run test to check if all issues have been resolved.

Import Setup successful

You can go ahead with your testing process. Happy testing!!!😀

Conclusion

In summary, incorporating Jest and installing the essential Jest packages in a React Vite application is a simple and uncomplicated process. By following a series of straightforward steps, developers can seamlessly integrate Jest into their projects and harness its robust testing features. With Jest successfully implemented, they can confidently create tests to guarantee the quality and accuracy of their React Vite applications.

Top comments (26)

Collapse
 
uwemisrael profile image
Uwem

This worked perfectly for me. If you have typescript path alias, you'll need to adjust your jest.config.js

My tsConfig fie

{
"baseUrl": ".",
    "paths": {
      "@app/*": ["src/*"]
    }
}
Enter fullscreen mode Exit fullscreen mode

jest.config.js

export default {
  preset: 'ts-jest',
  testEnvironment: 'jest-environment-jsdom',
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
    // process `*.tsx` files with `ts-jest`
  },
  rootDir: 'src',
  moduleNameMapper: {
    '\\.(gif|ttf|eot|svg|png)$': '<rootDir>/test/__ mocks __/fileMock.js',
    '^@app/(.*)$': '<rootDir>/$1',
  },
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yuripaz profile image
Yuri da Paz Simonin

unfortunately this feature is not working

Collapse
 
hannahadora profile image
Hannah Ejimofor

Sorry about that .. Have you found a way to get it working?

Collapse
 
thraizz profile image
Aron Schüler

Now if I only could get the transform for import { ReactComponent as MySvg } from "./MySvg.svg"; to work 🥲

Collapse
 
jukkahuuskonen profile image
Jukka Huuskonen

are you already using:
import MySvg from './MysSvg.svg?react;

or just wishing to get the old way to work?

Collapse
 
thraizz profile image
Aron Schüler

Wishing the old way to work.
But I can do that with the plugin vite-plugin-svgr, just register it as a plugin and you're good to go 😺

Collapse
 
urielbitton profile image
Uriel Bitton

you're a genius. This was such a nightmare when moving from CRA to Vite. thanks!

Collapse
 
hannahadora profile image
Hannah Ejimofor

Thank you 😊

Collapse
 
iamfranco profile image
Franco Chan

Amazing guide, thank you so much!! I'll probably come back here whenever I start a new vite jest project 😅

Collapse
 
hannahadora profile image
Hannah Ejimofor

✅😄

Collapse
 
septalfauzan profile image
Septa Alfauzan

Thank, it help me a lot

Collapse
 
hannahadora profile image
Hannah Ejimofor

I appreciate 😀

Collapse
 
ochukodotspace profile image
Ochuko

Thank you for this. It wasn't so straight forward for me, I had some dependency conflicts I had to figure out, but this article ultimately saved the day.

Collapse
 
hannahadora profile image
Hannah Ejimofor

Thank you

So happy to hear that

Collapse
 
shmbajaj profile image
shubhambajaj

Inside jest.config.ts, the property rootDir is not configured to "src"
which causes the error: "Could not load module, resolver: undefined".

To resolve the error either set the rootDir or adjust path to have "src" inside it.

[1] Set rootDir to "src"

jest.config.ts

{
rootDir: "src",
  moduleNameMapper: {
    '\\.(gif|ttf|eot|svg|png)$': '<rootDir>/test/__mocks__/fileMock.js',
  },
}
Enter fullscreen mode Exit fullscreen mode

[2] Adjust path to have "src" inside it

jest.config.ts

{
...,
  moduleNameMapper: {
    '\\.(gif|ttf|eot|svg|png)$': '<rootDir>/src/test/__mocks__/fileMock.js',
  },
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aliplutus profile image
aliplutus

did u solve that yest

Collapse
 
shmbajaj profile image
shubhambajaj
Collapse
 
brunocampos profile image
Bruno Campos

Thanks, Hanna! I was getting crazy looking for a solution like this.

Collapse
 
hannahadora profile image
Hannah Ejimofor

Thank you
I'm glad it helped

Collapse
 
ferchomuri profile image
Fernando Murillo

Hi everyone,

I'm new to Vite and Jest but I have some problems with SVG and CSS, and I fixed them with this code:

jest.config.ts

export default {
preset: "ts-jest”,
testEnvironment: "jest-environment-jsdom”,
transform: {
“^.+\\.tsx?$”: "ts-jest”,
},
rootDir: "src”,
moduleNameMapper: {
“\\.(gif|ttf|eot|svg|png)$”: “<rootDir>/test/__ mocks __/fileMock.js”,
“^@app/(.*)$”: “<rootDir>/$1”,
"\\.(css)$": "identity-obj-proxy",
},
}

Collapse
 
aliplutus profile image
aliplutus • Edited

SyntaxError: Cannot use import statement outside a module

github.com/aliscie/odoc/tree/unit-...

Image description

Collapse
 
pkatheti profile image
pradeep katheti

PASS src/test/App.spec.tsx
FAIL src/test/App.test.tsx
● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Enter fullscreen mode Exit fullscreen mode

this error even setup all thing

Collapse
 
sameerkali profile image
Sameer Faridi

its working for me, thanks alot

Collapse
 
hhourani27 profile image
Habib

Thank you for this tutorial. On small difference, I installed jest-environment-jsdom as a dev dependency (is there a reason not to?)

npm install jest-environment-jsdom --save-dev

Collapse
 
mohsincode profile image
Mohsin • Edited

Is it recommended to use Jest for a Vite project for unit and integration testing? Or is it better to go with another testing tool?

Collapse
 
johnw profile image
John Witt

How would this install process differ without using TypeScript? I have been learning to code the past nine months and I have not reviewed TypeScript yet. What's the best way to proceed?