"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
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);
});
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();
});
To run tests:
npm test
β³οΈ 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
After giving the project-name,
choose React > JavaScript
to initiate a project. Go inside the directory :
cd project-name
Install dependencies:
npm install
Now start the server:
npm run dev
It will be starting fresh like this π
Step 2: Install Jest
Install jest as a dev dependency:
npm install --save-dev jest
In package.json
add "test": "jest"
inside scripts,
"scripts": {
"test": "jest",
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
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
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'}}]],
};
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
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);
});
});
Execute the test command:
npm test
π₯³ 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
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 π
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
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
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
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" }],
],
};
To get helpful matcher like [toBeInTheDocument,
toBeInvalid,
toBeRequired,
toBeValid,
toBeVisible
], another dependency is needed:
npm install "@testing-library/jest-dom"
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();
});
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.
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)