Skip to content

Jest Aide-mémoire

Framework de test JavaScript agréable à utiliser, sans configuration.

01

Démarrage

Test de base

test/expect pour les assertions.

jest
test("adds numbers", () => {
  expect(1 + 2).toBe(3);
});

Describe

describe regroupe les tests liés.

jest
describe("Math", () => {
  test("add", () => expect(1+1).toBe(2));
  test("sub", () => expect(2-1).toBe(1));
});

Matchers

Matchers courants.

jest
expect(value).toBe(other);
expect(arr).toContain(item);
expect(obj).toEqual({a: 1});
expect(fn).toThrow();
expect(promise).resolves.toBe(42);
02

Fonctionnalités

Mock

jest.fn() crée des fonctions mock.

jest
const mockFn = jest.fn();
mockFn.mockReturnValue(42);
mockFn();
expect(mockFn).toHaveBeenCalled();

Async

Les tests asynchrones utilisent async/await.

jest
test("async", async () => {
  const data = await fetchData();
  expect(data).toBe("ok");
});

Before/After

Hooks de mise en place et de nettoyage.

jest
beforeEach(() => setup());
afterEach(() => cleanup());
afterAll(() => db.close());

Snapshot

Tests par snapshot pour les composants UI.

jest
expect(component).toMatchSnapshot();

Was this helpful?