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 testSimple assertion.
test('adds 1+2 to equal 3', () => { expect(sum(1,2)).toBe(3); });
Describe blockGroup tests.
describe('User utils', () => {
  test('formats name', () => {});
  test('validates email', () => {});
});

Matchers

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

Mocking

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

Async

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

Setup & Teardown

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