Jest ist ein modernes JavaScript-Testframework mit Fokus auf Einfachheit, Zero-Config-Setups und sofortige Snapshot-Tests.
Testausführung und CLI-Optionen (CLI Flags)
jest # Alle Tests ausfuehren
jest --watch # Tests im interaktiven Watch-Modus ausfuehren
jest --coverage # Code-Coverage-Bericht generieren
jest path/to/test.js # Bestimmte Testdatei ausfuehren
jest -t "test name pattern" # Tests nach Beschreibungszeichenfolge filtern
jest --runInBand # Tests sequenziell in einem einzigen Prozess ausfuehren
Haeufige Matcher (Common Matchers)
// Wahrheitswerte und Gleichheit
expect(val).toBe(42); // Strikte Gleichheit (Object.is)
expect(val).toEqual({ a: 1 }); // Tiefe strukturelle Gleichheit
expect(val).toStrictEqual({ a: 1 }); // Prueft zusaetzlich Typen-Prototypen
expect(val).toBeNull();
expect(val).toBeDefined();
expect(val).toBeTruthy();
expect(val).toBeFalsy();
// Zahlen und numerische Vergleiche
expect(val).toBeGreaterThan(3);
expect(val).toBeGreaterThanOrEqual(3.5);
expect(val).toBeCloseTo(0.3, 5); // Fliesskomma-Vergleich mit Praezision
// Zeichenketten und Arrays
expect(str).toMatch(/regex/);
expect(arr).toContain('item');
expect(arr).toHaveLength(3);
// Ausnahmen und Fehlerfaelle
expect(() => compileCode()).toThrow();
expect(() => compileCode()).toThrow(ConfigError);
Asynchroner Code (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');
});
Mock-Funktionen und Spies (jest.fn() und 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(); // Urspruengliche Implementierung wiederherstellen
Snapshot-Tests (Snapshot Testing)
test('renders correctly', () => {
const tree = renderer.create(<Button label="Submit" />).toJSON();
expect(tree).toMatchSnapshot();
});
Setup- und Teardown-Hooks
beforeAll(() => database.connect());
afterAll(() => database.disconnect());
beforeEach(() => database.clear());
afterEach(() => jest.clearAllMocks());