Jest 23.x Documentation

website·Indexed 43 days ago

https://archive.jestjs.io/

Documentation for Jest version 23.x, a JavaScript testing platform. Includes guides on global methods, the `expect` API, mock functions, ES6 class mocks, and configuration via `package.json` or `jest.config.js`. Covers integration with Webpack, React, React Native, and presets like `jest-puppeteer`, `jest-mongodb`, and `jest-dynamodb`.

Tokens
1.5M
Snippets
9.8K
Records
11.7K
Agent score
46%

What's inside Jest

  1. Overview of Jest JavaScript Testing Framework

    Jest is a JavaScript testing framework focused on simplicity and correctness. It is designed to work out of the box with minimal configuration and supports projects using Babel, TypeScript, Node, React, Angular, and Vue. Key architectural features include:

    • Isolated Execution: Tests are parallelized by running in their own processes to maximize performance and ensure unique global state.
    • Fast Execution: Jest optimizes runtimes by executing previously failed tests first and organizing runs based on file execution time.
    • Integrated Toolkit: Provides a comprehensive API (including it and expect) in a single package.
  2. Overview of Jest Testing Framework

    Jest is a JavaScript testing framework focused on simplicity and correctness. It is designed to work out of the box with minimal configuration and supports projects using Babel, TypeScript, Node, React, Angular, and Vue.
  3. Debug Jest execution and memory leaks

    Use these flags to troubleshoot Jest issues:

    • --debug: Prints debugging information about the Jest configuration.
    • --detectOpenHandles: Attempts to identify open handles that prevent Jest from exiting cleanly. This forces tests to run serially (--runInBand) and has a performance penalty.
    • --logHeapUsage: Logs heap usage after each test to help debug memory leaks. Should be used with --runInBand and --expose-gc.
    • --forceExit: Forces Jest to exit after tests complete. This is an 'escape-hatch' for resources that cannot be cleaned up; use --detectOpenHandles to find the root cause.
  4. Understand the difference between Jest snapshot testing and visual regression testing

    Snapshot testing in Jest is not pixel-based visual testing. Instead, it serializes values into text files and compares them using a diff algorithm. While visual regression tools compare screenshots of web pages pixel-by-pixel, Jest snapshots track changes in the serialized output of modules or components.
  5. Inspect mock function calls using the .mock property

    In Jest, mock functions expose a .mock property that contains metadata about how the function was called. The mock.calls array tracks every invocation, where each element is an array of arguments passed to that specific call. This allows developers to assert the number of calls, the specific arguments used in any call, or the arguments of the most recent invocation.
    // Assert the mock function was called at least once
    expect(mockFunc.mock.calls.length).toBeGreaterThan(0);
    
    // Assert the mock function was called at least once with specific arguments
    expect(mockFunc.mock.calls).toContainEqual([arg1, arg2]);
    
    // Assert the last call to the mock function used specific arguments
    expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1]).toEqual([
      arg1,
      arg2,
    ]);
    
    // Assert the first argument of the last call was exactly 42
    expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1][0]).toBe(42);
    
    // Use a snapshot or equality check to verify the exact sequence and arguments of all calls
    expect(mockFunc.mock.calls).toEqual([[arg1, arg2]]);
    
    // Verify the mock function's assigned name
    expect(mockFunc.getMockName()).toBe('a mock name');
  6. Inspect mock call history using the .mock property

    Every mock function has a .mock property that records data about its calls, including arguments, return values, and this context. It is also used to track instances created via the new keyword.
    const someMockFunction = jest.fn();
    
    // Check number of calls
    expect(someMockFunction.mock.calls.length).toBe(1);
    
    // Check arguments of the first call
    expect(someMockFunction.mock.calls[0][0]).toBe('first arg');
    
    // Check return value of the first call
    expect(someMockFunction.mock.results[0].value).toBe('return value');
    
    // Check number of times the function was instantiated with 'new'
    expect(someMockFunction.mock.instances.length).toBe(2);
  7. Initialize a Jest configuration file

    Run jest --init to generate a basic jest.config.js file. Jest will prompt you with a series of questions about your project to help configure the file with appropriate options.
    jest --init
  8. Implement a Jest Watch Plugin

    Jest watch plugins allow developers to hook into the test lifecycle and add custom interactive prompts to the watch mode menu. A plugin is a class that can implement apply, getUsageInfo, and run methods.
    class MyWatchPlugin {
      // Add hooks to Jest lifecycle events
      apply(jestHooks) {}
    
      // Get the prompt information for interactive plugins
      getUsageInfo(globalConfig) {}
    
      // Executed when the key from `getUsageInfo` is input
      run(globalConfig, updateConfigAndRun) {}
    }
  9. Initialize a Jest configuration file

    The --init flag generates a basic jest.config.js file. Jest will prompt you with a series of questions about your project to help configure the options.
    jest --init
  10. Inspect mock call data using the .mock property

    All mock functions created via jest.fn() have a .mock property that stores metadata about the function's usage. This is used to verify how functions were called, instantiated, or what they returned.
    const myMock = jest.fn();
    
    // Track instances created with 'new' or bound contexts
    const a = new myMock();
    const b = {};
    const bound = myMock.bind(b);
    bound();
    
    console.log(myMock.mock.instances); // [ <a>, <b> ]
    
    // Common assertions using .mock
    expect(someMockFunction.mock.calls.length).toBe(1); // Call count
    expect(someMockFunction.mock.calls[0][0]).toBe('first arg'); // First arg of first call
    expect(someMockFunction.mock.results[0].value).toBe('return value'); // First return value
    expect(someMockFunction.mock.instances.length).toBe(2); // Number of instantiations
  11. Discover curated Jest community extensions and resources

    The jest-community GitHub organization serves as a curated hub for high-quality Jest additions maintained by Jest collaborators. Key projects include vscode-jest (VS Code integration), jest-extended (additional matchers), and eslint-plugin-jest (linting for Jest tests). For a comprehensive list of all Jest-related projects and resources beyond this organization, refer to the awesome-jest repository.
    # Example: Explore the awesome-jest list for community resources
    # https://github.com/jest-community/awesome-jest
  12. Set the JSDOM URL and test failure exit code

    Two specific configuration keys for environment and process control:

    • testURL: Sets the URL for the jsdom environment (defaults to about:blank), affecting location.href.
    • testFailureExitCode: The exit code Jest returns when tests fail (defaults to 1). This does not affect errors caused by invalid configuration.