Riferimento rapido

Foglio di riferimento Jest Testing Framework

Guida di riferimento completa per Jest: opzioni CLI, matcher comuni, funzioni mock e spies, snapshot testing, test asincroni e hook di configurazione e pulizia.

· Pubblicato

Jest e un eccellente framework di testing per JavaScript focalizzato su semplicita, configurazione zero e test istantanei tramite snapshot.

Esecuzione dei test e opzioni CLI (CLI Flags)

jest                           # Esegue tutti i test
jest --watch                   # Esegue i test in modalita interattiva watch
jest --coverage                # Genera il report di copertura del codice
jest path/to/test.js           # Esegue uno specifico file di test
jest -t "test name pattern"    # Filtra i test in base alla stringa di descrizione
jest --runInBand               # Esegue i test in sequenza in un singolo processo

Matcher comuni (Common Matchers)

// Verita ed uguaglianza
expect(val).toBe(42);                  // Uguaglianza rigorosa (Object.is)
expect(val).toEqual({ a: 1 });         // Uguaglianza strutturale profonda
expect(val).toStrictEqual({ a: 1 });   // Controlla anche i prototipi dei tipi
expect(val).toBeNull();
expect(val).toBeDefined();
expect(val).toBeTruthy();
expect(val).toBeFalsy();

// Numeri e confronti numerici
expect(val).toBeGreaterThan(3);
expect(val).toBeGreaterThanOrEqual(3.5);
expect(val).toBeCloseTo(0.3, 5);       // Confronto aritmetico a virgola mobile

// Stringhe e array
expect(str).toMatch(/regex/);
expect(arr).toContain('item');
expect(arr).toHaveLength(3);

// Eccezioni ed errori
expect(() => compileCode()).toThrow();
expect(() => compileCode()).toThrow(ConfigError);

Codice asincrono (Asynchronous Code)

test('resolves with data', async () => {
  const data = await fetchData();
  expect(data).toHaveProperty('status', 200);
});

test('handles promise rejection', async () => {
  await expect(fetchData('invalid')).rejects.toThrow('Not Found');
});

Funzioni Mock e Spies (jest.fn() & Spies)

const mockFn = jest.fn().mockReturnValue('mocked result');
mockFn('arg1');

expect(mockFn).toHaveBeenCalledTimes(1);
expect(mockFn).toHaveBeenCalledWith('arg1');

// Mocking module methods
const spy = jest.spyOn(api, 'getUser').mockResolvedValue({ id: 1, name: 'Alice' });
const user = await api.getUser(1);
expect(spy).toHaveBeenCalled();
spy.mockRestore(); // Ripristina l'implementazione originale

Test degli snapshot (Snapshot Testing)

test('renders correctly', () => {
  const tree = renderer.create(<Button label="Submit" />).toJSON();
  expect(tree).toMatchSnapshot();
});

Setup e Teardown

beforeAll(() => database.connect());
afterAll(() => database.disconnect());
beforeEach(() => database.clear());
afterEach(() => jest.clearAllMocks());

Riferimenti correlati

Argomenti correlati