Jest este un cadru complet de testare JavaScript concentrat pe simplitate, configurare zero si teste rapide de snapshot.
Executia testelor si optiuni CLI (CLI Flags)
jest # Ruleaza toate testele
jest --watch # Ruleaza testele in modul interactiv watch
jest --coverage # Genereaza raportul de acoperire a codului
jest path/to/test.js # Ruleaza un fisier specific de test
jest -t "test name pattern" # Filtreaza testele dupa sablonul descrierii
jest --runInBand # Ruleaza testele secvential intr-un singur proces
Potrivitori uzuali (Common Matchers)
// Veridicitate si egalitate
expect(val).toBe(42); // Egalitate stricta (Object.is)
expect(val).toEqual({ a: 1 }); // Egalitate structurala profunda
expect(val).toStrictEqual({ a: 1 }); // Verifica suplimentar prototipurile de tip
expect(val).toBeNull();
expect(val).toBeDefined();
expect(val).toBeTruthy();
expect(val).toBeFalsy();
// Numere si comparatii numerice
expect(val).toBeGreaterThan(3);
expect(val).toBeGreaterThanOrEqual(3.5);
expect(val).toBeCloseTo(0.3, 5); // Comparatie a numerelor in virgula mobila
// Siruri de caractere si tablouri
expect(str).toMatch(/regex/);
expect(arr).toContain('item');
expect(arr).toHaveLength(3);
// Exceptii si erori
expect(() => compileCode()).toThrow();
expect(() => compileCode()).toThrow(ConfigError);
Cod asincron (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');
});
Functii Mock si 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(); // Restaureaza implementarea originala
Testare instantanee (Snapshot Testing)
test('renders correctly', () => {
const tree = renderer.create(<Button label="Submit" />).toJSON();
expect(tree).toMatchSnapshot();
});
Initializare si curatare (Setup and Teardown)
beforeAll(() => database.connect());
afterAll(() => database.disconnect());
beforeEach(() => database.clear());
afterEach(() => jest.clearAllMocks());