DEV Community

Cover image for πŸ§ͺ Setup Jest with (Webpack, Vite)
Jorjis Hasan
Jorjis Hasan

Posted on

πŸ§ͺ Setup Jest with (Webpack, Vite)

"You should write tests before you write the code."
⏀ creator of TDD

Why Jest?

Jest is a powerful one-stop testing library that can be paired with React, React-Native, Angular, Vue, and Svelte. Almost all frameworks are powered by JavaScript. Its simplicity and fast learning curve make it a top choice for developers. Within an hour, you can start writing tests using their well docs resources. Companies like Meta, Amazon, and Microsoft rely on Jest for its robust features like mocking, snapshot testing, and code coverage.

Once you learn to test, you feel software better. How things work and how it is supposed to be. This keeps you confident while building software, no matter how big the software is.

Enough talking. Let's dive into the steps to set up Jest in the popular bundlers Webpack and Vite.


⛳️ Jest with Webpack

I'll use Webpacks popular template create-react-app for more straightforward setup. Jest comes out of the box by default in Webpack. Quickly start the project, and you'll be all set to write tests. To quick Start:

npx create-react-app my-app
cd my-app
npm start
Enter fullscreen mode Exit fullscreen mode

By running the command, you'll get a boilerplate scaffold file structure and a live preview. Head into the project, you'll find src/ directory. Inside the src/ directory, you can write your tests. It's best practice to create a separate folder, __tests__/ and keep your test files inside the subdirectory src/__tests__/...*testfiles.

Any file with this convention filename.[test/specs].[js/tsx/jsx] will be treated as a test file.

Let's try two types of testing: basic function and component testing. We'll create two files inside the src/__tests__/... directory.

sum.test.js
import sum from "../sum";

test("Testing sum function", () => {
  expect(sum(2, 3)).toBe(5);
});

Enter fullscreen mode Exit fullscreen mode

Header.test.js
import { render, screen } from "@testing-library/react";
import Header from "../components/Header";

test("Check Header load with specific text: 'Hey, Good Developers 😜'", () => {
  // render
  render(<Header />);

  // assertion
  const targetElement = screen.getByText("Hey, Good Developers 😜");

  // expect
  expect(targetElement).toBeInTheDocument();
});


Enter fullscreen mode Exit fullscreen mode

To run tests:

npm test
Enter fullscreen mode Exit fullscreen mode

Webpack - ScreenRecording


⛳️ Jest with Vite

Vite is likely ~10x faster than Webpack in a production build and running development server. But Vite uses its own testing library called Vitest. Which is also good. So, we need to configure Jest separately.

Vite excels at speed, while Jest maintains consistency. If Vite and Jest clock together, they would have a superpower. Let's step into power:

Step 1: Install Vite with React

Install Vite via npm:

npm create vite@latest
Enter fullscreen mode Exit fullscreen mode

After giving the project-name, choose React > JavaScript to initiate a project. Go inside the directory :

cd project-name
Enter fullscreen mode Exit fullscreen mode

Install dependencies:

npm install
Enter fullscreen mode Exit fullscreen mode

Now start the server:

npm run dev
Enter fullscreen mode Exit fullscreen mode

It will be starting fresh like this πŸ‘‡

Vite Dev Server

Step 2: Install Jest

Install jest as a dev dependency:

npm install --save-dev jest
Enter fullscreen mode Exit fullscreen mode

In package.json add "test": "jest" inside scripts,

  "scripts": {
    "test": "jest",
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint .",
    "preview": "vite preview"
  },
Enter fullscreen mode Exit fullscreen mode

Since vite by default uses test library called vitest. To use jest, we need Babel for transpilation. To use Babel, install required dependencies:

npm install --save-dev babel-jest @babel/core @babel/preset-env
Enter fullscreen mode Exit fullscreen mode

Configure Babel to target your current version of Node by creating a babel.config.cjs file in the root of your project:

// project-name/babel.config.cjs
module.exports = {
  presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
Enter fullscreen mode Exit fullscreen mode

You can use type definitions which ships with Jest and will update each time you update Jest. Install the @jest/globals package:

npm install --save-dev @jest/globals 
Enter fullscreen mode Exit fullscreen mode

And import the APIs from it:

// src/__tests__/sum.test.js

import { describe, expect, test } from "@jest/globals";
import sum from "../sum";

describe("sum module", () => {
  test("adds 1 + 2 to equal 3", () => {
    expect(sum(1, 2)).toBe(3);
  });
});

Enter fullscreen mode Exit fullscreen mode

Execute the test command:

npm test
Enter fullscreen mode Exit fullscreen mode

Testing sum() function

πŸ₯³ You're good to go with Jest for basic testing. Now, you can test basic functions. But if you want to test components(headers, body, footer), we need a browser-like environment because HTML is generally rendered on browsers. So we must configure jest by going through step 3 πŸ‘‡.

Step 3: Config Jest

Initiate jest :

npx jest --init
Enter fullscreen mode Exit fullscreen mode

Choose these options carefully: jsdom(browser-like) > babel. After executing these commands, Jest will configure by creating a file jest.config.mjs. Just like this πŸ‘‡

CloseUp options

For DOM manipulation, we need to have a browserlike environment. For that, it needs another library called jsdom. To get started with the JSDOM test environment:

npm install --save-dev jest-environment-jsdom
Enter fullscreen mode Exit fullscreen mode

To get started with React Testing Library, you'll need to install it together with its peerDependency @testing-library/dom:

npm install --save-dev @testing-library/react @testing-library/dom
Enter fullscreen mode Exit fullscreen mode

After installing the React testing library, To support the .jsx syntax @babel/preset-react, this package needs to install:

npm install --save-dev @babel/preset-react
Enter fullscreen mode Exit fullscreen mode

Include this plugin in babel.config.cjs, and update the babel config file with this:

// project-name/babel.config.cjs
module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    ["@babel/preset-react", { runtime: "automatic" }],
  ],
};
Enter fullscreen mode Exit fullscreen mode

To get helpful matcher like [toBeInTheDocument,toBeInvalid,toBeRequired,
toBeValid,toBeVisible ], another dependency is needed:

npm install "@testing-library/jest-dom"
Enter fullscreen mode Exit fullscreen mode

And import the APIs from it:

// src/__tests__/Header.test.js

import { expect, test } from "@jest/globals";
import Header from "../component/Header";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";

test("Check Header load with specific text 'Hey, Good Developers 😜'", () => {
  // render
  render(<Header />);

  // assertion
  const targetElement = screen.getByText("Hey, Good Developers 😜");

  // expect
  expect(targetElement).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

Wala <πŸŽ‰/> All set up has βœ…Done. Now you've achieved a superpower. `Jest and Vite tune in together seamlessly, powering the application development process.

In case you get any error on following whole process, just comment down πŸ’¬. I'll try to resolve it.

Vite-Component-Test-Screenrecord

PS: If anyone is new to testing, I'll hold your hand from here until the end of the series. I dedicated the whole series on 'testing'.

Top comments (0)