How to add Jest to your Vite-React project?

How to add Jest to your Vite-React project?

Add jest to a react project scaffolded using vitejs

Vite is the development server that is very fast as it uses native ES Modules instead of bundling. Vite has a starter template for React applications.

Projects created with Create React App have out-of-the-box support for unit tests but the Vite template doesn't include any test runner; we have to add one.
There is also an issue added on vitejs' GitHub repo about first-class jest integration.

Jest is a test runner, which gives you the ability to run tests with Jest from the command line. In addition, Jest offers you functions for test suites, test cases, and assertions.

This tutorial shows you how to add unit testing to a newly generated React Vite project. Follow these steps:

  1. Create a react project using vite (if you haven't already)

    npm init vite@latest
    

    Then select react from template options jest-setup.png

  2. Add jest to your project

    npm install --save-dev jest
    
  3. Add Babel
    By default, Jest doesn't understand JSX/Typescript files, so we need to transpile them before and pass the transpilation step as configuration.

    npm install --dev babel-jest @babel/core @babel/preset-env
    

    And add this babel preset in babel.config.js

    // babel.config.js
    module.exports = {
     presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
    };
    
  4. Add vite-jest
    This package comes with a Jest transformer, a Jest reporter, a Jest preset, and a simple CLI wrapper of the jest command.

    npm install vite-jest
    
  5. Add test script
    Add a test script using "vite-jest" in your package.json. Add --watch flag as well to watch tests if you'd like.

    //package.json
    {
      "scripts": {
          //other scripts here
          "test": "vite-jest --watch"
      },
    }
    
  6. Add some tests to check if everything works
    Create a file called sum.js and add the following function to it. We will import this in a test file to check if imports work properly in tests.

    // sum.js
    export default function sum(a, b) {
       return a + b;
    }
    

    Add a test file - app.test.js and import sum from sum.js. Add a test for this function.

    // app.test.js
    import sum from "./sum.js";
    test('adds 1 + 2 to equal 3', () => {
       expect(sum(1, 2)).toBe(3);
    });
    

    Run the test command to test this function.

    npm run test
    

    You should see that the test has passed. jest-success.png

I have set up a repo, you can fork it and check it out locally.

You can reach out to me at my twitter or linkedin