Skip to content

Jest Spickzettel

Angenehmes JavaScript-Test-Framework ohne Konfigurationsaufwand.

01

Einstieg

Einfacher Test

test/expect für Assertions.

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

describe

describe gruppiert zusammengehörige Tests.

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

Matcher

Gebräuchliche Matcher.

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

Funktionen

Mocks

jest.fn() erstellt Mock-Funktionen.

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

Asynchron

Asynchrone Tests verwenden async/await.

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

Before/After

Hooks für Setup und Teardown.

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

Snapshots

Snapshot-Tests für UI-Komponenten.

jest
expect(component).toMatchSnapshot();

Was this helpful?