Jest
About 889 wordsAbout 3 min
ReactJestUnit test
2025-02-08
What is Jest
Jest is a JavaScript testing framework primarily used for testing React applications, but it's also powerful enough for general JavaScript and TypeScript testing. It’s fast, easy to configure, and comes with built-in features like mocking, snapshots, and parallel test execution.
Jest Core Features
- Zero Configuration: Jest works out of the box with most JavaScript projects without requiring additional setup.
- Built-in Mocks: Jest allows easy mocking of functions, modules, timers, and even API calls.
- Snapshot Testing: Compare component output to a saved snapshot to detect unintended changes.
- Code Coverage Reports: Jest can generate detailed test coverage reports, helping you track untested parts of your code.
- Parallel Test Execution: Jest runs tests in parallel, significantly improving performance.
Installation & Basic useage
- Installing Jest
#For React projects (using Create React App), Jest comes pre-installed.
npm install --save-dev jest #Installing Jest
npm install --save-dev @types/jest ts-jest #For TypeScript support
- Jest can be configured via package.json, jest.config.js, or jest.config.ts. Configuration is optional.
module.exports = {
verbose: true,
testEnvironment: "jsdom", // "node" for backend testing
setupFilesAfterEnv: ["./jest.setup.js"],
};
- Writing Tests in Jest
Jest follows a BDD-style (Behavior-Driven Development) syntax.
//functionalities code
function sum(a, b) {
return a + b;
}
module.exports = sum;
//test code
const sum = require("./sum");
test("adds 1 + 2 to equal 3", () => {
expect(sum(1, 2)).toBe(3);
});
npx jest # run jest
If the test passed, and Jest shows a green PASS message in the shell terminal, otherwise, jest clearly shows why the test failed with red fail.
You can also output the result into a file like json or xml.
- ✅ Save test results: npx jest --json --outputFile=jest-results.json
- ✅ Save coverage report: npx jest --coverage --coverageReporters="json-summary"
- ✅ Configure Jest for automatic reporting via jest.config.js
Jest Matchers
Jest provides many matchers for writing flexible tests.
Common Matchers
test("basic matchers", () => {
expect(4 + 4).toBe(8); // Exact match
expect(4 + 4).not.toBe(10); // Not equal
expect({ name: "John" }).toEqual({ name: "John" }); // Object comparison
expect(null).toBeNull(); // Checks null
expect(undefined).toBeUndefined();
expect(true).toBeTruthy();
expect(0).toBeFalsy();
});
Number & String Matchers
test("number matchers", () => {
expect(10).toBeGreaterThan(5);
expect(10).toBeLessThan(20);
expect(10).toBeGreaterThanOrEqual(10);
expect("Hello Jest").toMatch(/Jest/); // Regex matching
});
Array & Object Matchers
test("array and object matchers", () => {
expect([1, 2, 3]).toContain(2);
const user = { name: "Alice", age: 30 };
expect(user).toHaveProperty("name");
expect(user).toHaveProperty("age", 30);
});
Jest Mocks & Spies
Mocking allows you to isolate a unit of code by replacing dependencies with fake implementations.
Mocking Functions
const mockFn = jest.fn();
test("mock function", () => {
mockFn("Hello");
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith("Hello");
});
Mocking a Module
jest.mock("./api"); // Automatically mocks the module
const api = require("./api");
test("mock API call", async () => {
api.getData.mockResolvedValue({ name: "Alice" });
const data = await api.getData();
expect(data.name).toBe("Alice");
});
Spying on Functions
const obj = {
method: (msg) => `Hello ${msg}`,
};
jest.spyOn(obj, "method");
test("spy on method", () => {
obj.method("World");
expect(obj.method).toHaveBeenCalledWith("World");
});
Asynchronous Testing
Testing Promises
test("async function test", async () => {
const fetchData = () => Promise.resolve("Data");
await expect(fetchData()).resolves.toBe("Data");
});
Testing API Calls with Mocks
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ data: "test" }),
})
);
test("mock fetch API", async () => {
const response = await fetch();
const data = await response.json();
expect(data).toEqual({ data: "test" });
});
Snapshot Testing
A typical snapshot test case renders a UI component, takes a snapshot, then compares it to a reference snapshot file stored alongside the test. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated to the new version of the UI component.
React Snapshot Testing
import React from "react";
import renderer from "react-test-renderer";
import Button from "./Button"; // Sample React component
test("Button matches snapshot", () => {
const tree = renderer.create(<Button label="Click me" />).toJSON();
expect(tree).toMatchSnapshot();
});
npx jest --updateSnapshot #Run Jest and update snapshots if necessary
Jest with React Testing Library (RTL)
Jest works well with React Testing Library for testing React components.
Installing React Testing Library
npm install --save-dev @testing-library/react
Writing Component Tests
import { render, screen, fireEvent } from "@testing-library/react";
import Button from "./Button";
test("renders button and handles click", () => {
const handleClick = jest.fn();
render(<Button label="Click Me" onClick={handleClick} />);
const button = screen.getByText("Click Me");
fireEvent.click(button);
expect(handleClick).toHaveBeenCalled();
});
Code Coverage with Jest
Jest provides a code coverage report to see which parts of your code are tested.
Running Tests with Coverage
npx jest --coverage
Output will print as follow:
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---|---|---|---|---|---|
All files | 80.00% | 75.00% | 66.67% | 80.00% | |
sum.js | 100.00% | 50.00% | 100.00% | 100.00% | 3 |
multiply.js | 50.00% | 50.00% | 50.00% | 50.00% | 5,6 |
Customizing Coverage
module.exports = {
collectCoverage: true,
collectCoverageFrom: ["src/**/*.js"],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
},
};
Jest Best Practices
- Keep Tests Independent – Avoid shared states between tests.
- Use Mocks Wisely – Mock only what's necessary to avoid over-mocking.
- Write Descriptive Test Names – test("renders correctly") is better than test("test 1").
- Use Coverage Reports – Ensure sufficient test coverage.
- Run Tests in Watch Mode – npx jest --watch for efficient test development.
You can learn more by click here