ITSkillsCenter
Développement Web

Tests automatisés avec Jest : fiabiliser son code JavaScript

2 دقائق للقراءة
Miniature - Tests automatisés avec Jest : fiabiliser son code JavaScript

Ce que vous saurez faire à la fin

  1. Installer Jest et écrire le premier test
  2. Utiliser les matchers essentiels
  3. Mocker fonctions, modules, timers
  4. Tester du code async proprement
  5. Couverture 80 %+ et CI GitHub Actions

Étape 1 — Installation

npm install --save-dev jest @types/jest ts-jest
npx jest --init
// jest.config.js
module.exports = {
  testEnvironment: "node",
  preset: "ts-jest",
  coverageThreshold: {
    global: { branches: 80, functions: 85, lines: 85 }
  },
};

Étape 2 — Premier test

// src/math.js
export function tva(ht, taux = 0.18) {
  return Math.round(ht * (1 + taux));
}

// src/math.test.js
import { tva } from "./math.js";

describe("tva", () => {
  test.each([
    [1000, 0.18, 1180],
    [500, 0.10, 550],
    [0, 0.18, 0],
  ])("tva(%i, %f) = %i", (ht, taux, attendu) => {
    expect(tva(ht, taux)).toBe(attendu);
  });
});

Étape 3 — Matchers

expect(v).toBe(exact);
expect(obj).toEqual({a: 1});
expect(str).toMatch(/^FCFA/);
expect(liste).toContain("Dakar");
expect(liste).toHaveLength(3);
expect(() => fn()).toThrow("erreur");
expect(n).toBeGreaterThan(100);
expect(n).toBeCloseTo(3.14, 2);

Étape 4 — Tests async

test("fetch OK", async () => {
  const data = await fetchClient(42);
  expect(data.id).toBe(42);
});

test("rejette", async () => {
  await expect(fetchClient()).rejects.toThrow("id requis");
});

Étape 5 — Mocks de fonctions

const repo = { findById: jest.fn() };
repo.findById.mockResolvedValue({ id: 1, nom: "SARL" });

const c = await service.lire(1);
expect(repo.findById).toHaveBeenCalledWith(1);

Étape 6 — Mock d’un module

jest.mock("axios");
import axios from "axios";

test("appel API", async () => {
  axios.get.mockResolvedValue({ data: { taux: 18 } });
  const taux = await fetchTaux();
  expect(taux).toBe(18);
});

Étape 7 — Timers factices

jest.useFakeTimers();

test("timeout 30 min", () => {
  const cb = jest.fn();
  setTimeout(cb, 30 * 60 * 1000);
  jest.advanceTimersByTime(30 * 60 * 1000);
  expect(cb).toHaveBeenCalled();
});

Étape 8 — Setup/teardown

beforeAll(async () => { db = await connect(); });
afterAll(async () => { await db.end(); });
beforeEach(async () => { await db.query("TRUNCATE clients"); });
afterEach(() => { jest.clearAllMocks(); });

Étape 9 — Couverture

npx jest --coverage
# coverage/lcov-report/index.html
# Échoue si seuils coverageThreshold non atteints

Étape 10 — CI

name: Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: "20", cache: "npm" }
      - run: npm ci
      - run: npm test -- --coverage --ci

Checklist

✓ 1 test = 1 comportement
✓ Arrange / Act / Assert séparés
✓ beforeEach pour nettoyer l'état
✓ Mock uniquement les dépendances externes
✓ Couverture >= 80%
✓ Tests rapides (< 2 min au total)
Besoin d'un site web ?

Confiez-nous la Création de Votre Site Web

Site vitrine, e-commerce ou application web — nous transformons votre vision en réalité digitale. Accompagnement personnalisé de A à Z.

À partir de 250.000 FCFA
Parlons de Votre Projet
Publicité