Jest Basics
Essential Jest testing framework commands and syntax.
Test Structure
Basic test
describe("Test Suite", () => {
test("test case", () => {
expect(2 + 2).toBe(4);
});
});
Alternative syntax
it("should work", () => {
expect(true).toBeTruthy();
});
Common Matchers
Equality
expect(value).toBe(4);
expect(obj).toEqual({ a: 1 });
Truthiness
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeUndefined();
Numbers
expect(value).toBeGreaterThan(3);
expect(value).toBeLessThan(5);
expect(value).toBeCloseTo(0.3);
Arrays & Strings
Arrays
expect(arr).toContain("item");
expect(arr).toHaveLength(3);
Strings
expect(str).toMatch(/pattern/);
expect(str).toContain("substring");
Objects
expect(obj).toHaveProperty("key");
expect(obj).toMatchObject({ a: 1 });
Running Tests
Run all tests
npx jest
Watch mode
npx jest --watch
Coverage
npx jest --coverage
Specific file
npx jest mytest.test.js
Update snapshots
npx jest -u