We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie jest-guide

Jest Guide

[testing][unit-test]
JavaScript / TypeScript
Install
npm install -D jest @types/jest ts-jest
npx ts-jest config:init

Jest comes with everything: test runner, assertions, mocking, coverage, and snapshots.

Key concepts: describe, it/test, expect, and extensive matchers library.

Mocking: jest.fn(), jest.spyOn(), jest.mock(). Jest hoists mock calls automatically.

Setup

Basic test· Simple assertion.
test('adds 1+2 to equal 3', () => { expect(sum(1,2)).toBe(3); });
Describe block· Group tests.
describe('User utils', () => {
  test('formats name', () => {});
  test('validates email', () => {});
});

Matchers

Common matchers· Assert different types.
expect(value).toBe(42);
expect(obj).toEqual({a:1});
expect(arr).toContain('item');
expect(fn).toHaveBeenCalledWith('arg');

Mocking

Mock function· Create and assert on mock.
const mock = jest.fn();
mock('hello');
expect(mock).toHaveBeenCalledWith('hello');
expect(mock).toHaveBeenCalledTimes(1);
Mock return value· Control mock return.
const mock = jest.fn().mockReturnValue(42);
const asyncMock = jest.fn().mockResolvedValue({data:'ok'});
Spy on method· Wrap existing method.
const spy = jest.spyOn(console, 'log');
console.log('test');
expect(spy).toHaveBeenCalledWith('test');
spy.mockRestore();
Mock module· Replace entire module.
jest.mock('../api');
import { fetchUsers } from '../api';
(fetchUsers as jest.Mock).mockResolvedValue([{id:1}]);

Async

Async test· Test promises.
test('fetches users', async () => {
  const users = await fetchUsers();
  expect(users).toHaveLength(3);
});

Setup & Teardown

Setup/teardown· Run before each test.
beforeEach(() => { jest.clearAllMocks(); });
afterEach(() => { db.disconnect(); });