jest
Write reliable JavaScript tests with Jest: unit tests, mocking, snapshots, coverage, and CI integration. Use for JS/TS testing.
Jest
Testing JavaScript and TypeScript with Jest.
Quick Start
npm i -D jest @types/jest ts-jest
npx jestWhen to Use
- Unit tests for JS/TS code
- React/Node component logic
- API and utility function testing
- Coverage and regression suites
Best Practices
Test Structure
- Name tests by behavior: `test('adds numbers')`
- Arrange, act, assert per test
- One behavior per test
- Colocate or use `__tests__`
Matchers & Assertions
- Use natural matchers (`toBe`, `toEqual`, `toContain`)
- Use `expect` with descriptive messages
- Test edge cases and errors
- Prefer `toEqual` for objects
Mocking
- Mock external modules and side effects
- Use `jest.fn()` and `jest.spyOn()`
- Reset mocks between tests (`clearMocks`)
- Avoid over-mocking your own code
Coverage & CI
- Set coverage thresholds
- Run in CI on every PR
- Use `--ci` and `--coverage`
- Keep tests fast and isolated
Dependencies
npm i -D jest @types/jest ts-jest
# React: @testing-library/reactExamples
// Basic test
function add(a: number, b: number) {
return a + b;
}
test("adds two numbers", () => {
expect(add(2, 3)).toBe(5);
});// Mocking a module
import { fetchUsers } from "./api";
jest.mock("./api");
test("renders users", async () => {
fetchUsers.mockResolvedValue([{ id: 1, name: "Alice" }]);
const users = await loadUsers();
expect(users).toHaveLength(1);
});// Parameterized tests
test.each([
[1, 1, 2],
[2, 3, 5],
[-1, 1, 0],
])("adds %i + %i = %i", (a, b, expected) => {
expect(add(a, b)).toBe(expected);
});// Spy and error test
const spy = jest.spyOn(console, "error").mockImplementation(() => {});
expect(() => risky()).toThrow();
spy.mockRestore();Step-by-Step
1. Install Jest and configure for your stack.
2. Add the test script and coverage thresholds.
3. Write focused unit tests.
4. Mock external dependencies.
5. Add edge case and error tests.
6. Run with `--coverage` and review gaps.
7. Wire Jest into CI.
8. Keep tests deterministic and fast.
Validation
1. All tests pass locally and in CI
2. Coverage meets the threshold
3. Mocks are reset between tests
4. No tests depend on network or timers
5. Failures pinpoint the behavior
Troubleshooting
- Flaky tests: remove shared state and timing.
- Over-mocked: mock only boundaries, not internals.
- Slow suite: use `--maxWorkers` and isolate heavy tests.
Jest (Джест)
Тестирование JavaScript и TypeScript через Jest.
Быстрый старт
npm i -D jest @types/jest ts-jest
npx jestКогда использовать
- Юнит-тесты JS/TS кода
- Логика React/Node компонентов
- Тестирование API и утилит
- Покрытие и регрессионные сьюты
Лучшие практики
Структура тестов
- Имена по поведению: `test('adds numbers')`
- Arrange, act, assert на тест
- Одно поведение на тест
- Colocate или `__tests__`
Матчеры и ассерты
- Естественные матчеры (`toBe`, `toEqual`, `toContain`)
- `expect` с описательными сообщениями
- Edge cases и ошибки
- Для объектов — `toEqual`
Моки
- Мокайте внешние модули и сайд-эффекты
- `jest.fn()` и `jest.spyOn()`
- Сброс моков между тестами (`clearMocks`)
- Не перемокивайте свой код
Покрытие и CI
- Пороги покрытия
- CI на каждом PR
- `--ci` и `--coverage`
- Быстрые и изолированные тесты
Зависимости
npm i -D jest @types/jest ts-jest
# React: @testing-library/reactПримеры
// Базовый тест
function add(a: number, b: number) {
return a + b;
}
test("adds two numbers", () => {
expect(add(2, 3)).toBe(5);
});// Мок модуля
import { fetchUsers } from "./api";
jest.mock("./api");
test("renders users", async () => {
fetchUsers.mockResolvedValue([{ id: 1, name: "Alice" }]);
const users = await loadUsers();
expect(users).toHaveLength(1);
});// Параметризованные тесты
test.each([
[1, 1, 2],
[2, 3, 5],
[-1, 1, 0],
])("adds %i + %i = %i", (a, b, expected) => {
expect(add(a, b)).toBe(expected);
});// Spy и тест ошибки
const spy = jest.spyOn(console, "error").mockImplementation(() => {});
expect(() => risky()).toThrow();
spy.mockRestore();Пошаговое руководство
1. Установите Jest и настройте под ваш стек.
2. Добавьте test-скрипт и пороги покрытия.
3. Напишите сфокусированные юнит-тесты.
4. Мокайте внешние зависимости.
5. Добавьте edge case и error тесты.
6. Прогоните с `--coverage` и просмотрите пробелы.
7. Подключите Jest в CI.
8. Держите тесты детерминированными и быстрыми.
Валидация
1. Все тесты проходят локально и в CI
2. Покрытие соответствует порогу
3. Моки сбрасываются между тестами
4. Нет тестов на сеть или таймеры
5. Фейлы указывают на поведение
Устранение неполадок
- Флаки: уберите общее состояние и тайминг.
- Пере-моки: мокайте границы, не внутренности.
- Медленный сьют: `--maxWorkers` и изоляция тяжёлых тестов.