Jest Basics for React
In this page:
describe("group name", () => {
test("description", () => {
expect(actual).toBe(expected);
expect(objectValue).toEqual({ key: "value" });
});
});
Writing a Basic Test with test() and expect()
A Jest test is a call to test() (or its alias it()) with a description string and a function containing the test logic. Inside, expect(value) starts an assertion, chained with a matcher like .toBe() to check the actual result against what you expected.
Example: Writing a Basic Test with test() and expect()
// Run in your local React project (npm install required)
function add(a, b) { return a + b; }
test('adds two numbers correctly', () => {
expect(add(2, 3)).toBe(5);
});
toBe vs. toEqual
toBe checks strict equality (===), which works for primitives but fails for objects/arrays even with identical contents, since two separately-created objects are never === equal. toEqual instead performs a deep comparison, checking that the actual VALUES match, regardless of object identity.
Example: toBe vs. toEqual
// Run in your local React project (npm install required)
test('primitive comparison uses toBe', () => {
expect(2 + 2).toBe(4);
});
test('object comparison uses toEqual', () => {
expect({ name: 'Asha' }).toEqual({ name: 'Asha' }); // passes
// expect({ name: 'Asha' }).toBe({ name: 'Asha' }); // would fail!
});
Grouping Tests with describe()
describe() groups related test() calls under one shared label, making a test file's output organized and easier to scan, especially as the number of tests grows. describe blocks can also be nested for further organization.
Example: Grouping Tests with describe()
// Run in your local React project (npm install required)
describe('add function', () => {
test('adds positive numbers', () => {
expect(add(2, 3)).toBe(5);
});
test('adds negative numbers', () => {
expect(add(-1, -1)).toBe(-2);
});
});
- Confusing toBe (strict equality, ===) with toEqual (deep equality for objects/arrays).
- Forgetting test files need to match Jest's expected naming pattern (like *.test.js) to be picked up automatically.
- Not using describe() blocks to group related tests, making large test files hard to navigate.
- Jest is a JavaScript test runner, commonly paired with React Testing Library for component tests.
- test() (or it()) defines an individual test case; describe() groups related tests together.
- expect(value).matcher() makes assertions, like toBe, toEqual, or toBeInTheDocument (from Testing Library's extensions).
- Jest auto-discovers test files matching common naming patterns, like Component.test.js.
Requires npm install jest (or comes pre-configured with Create React App/Vite templates) — runs in Node, not this browser sandbox.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: