Jest Cheat Sheet

Here’s a cheat sheet for Jest, a popular JavaScript testing framework:

Installation

Install Jest:

npm install --save-dev jest

Configuring Jest

Create Jest Configuration File (Optional):

npx jest --init

Writing Tests

Test File Naming Convention:

  • Test files should have names ending with .test.js or .spec.js.

Basic Test:

test('Description of the test', () => {
  // Test code
});

Async Test:

test('Async test', async () => {
  const result = await someAsyncFunction();
  expect(result).toBe(expectedValue);
});

Matchers

Common Matchers:

expect(value).toBe(expectedValue);
expect(value).toEqual(expectedObject);
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();

Numbers and Comparisons:

expect(value).toBeGreaterThan(expectedValue);
expect(value).toBeLessThan(expectedValue);

Strings:

expect(string).toMatch(/pattern/);
expect(string).toContain(substring);

Mock Functions

Create a Mock Function:

const mockFunction = jest.fn();

Assert Mock Function Calls:

expect(mockFunction).toHaveBeenCalled();
expect(mockFunction).toHaveBeenCalledWith(arg1, arg2);
expect(mockFunction).toHaveBeenCalledTimes(expectedCount);

Setup and Teardown

Before and After Each Test:

beforeEach(() => {
  // Setup code
});

afterEach(() => {
  // Teardown code
});

Before and After All Tests:

beforeAll(() => {
  // Setup code
});

afterAll(() => {
  // Teardown code
});

Test Suites and Descriptions

Describe a Test Suite:

describe('Suite description', () => {
  // Nested tests or describe blocks
});

Running Tests

Run All Tests:

npx jest

Run Specific Tests:

npx jest myTestFile.test.js

Watch Mode

Run in Watch Mode:

npx jest --watch

Coverage Reporting

Generate Coverage Report:

npx jest --coverage

This cheat sheet covers some essential features of Jest for writing and running tests. Refer to the Jest documentation for more in-depth information and advanced features.