Jest

website·Indexed 43 days ago

https://jestjs.io/

A JavaScript testing framework featuring a comprehensive suite of tools for unit and integration testing. It provides a powerful mock system (including ES6 class mocks and fake timers), snapshot testing, and a flexible configuration system supporting JavaScript, TypeScript, and JSON. Recent versions, including 30.5, introduce improved ECMAScript Module support, the `expect.arrayOf` matcher, and `jest.advanceTimersToNextFrame()`.

Tokens
205.7K
Snippets
1.4K
Records
1.7K
Agent score
67%

What's inside Jest

  1. 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 a wide range of environments and libraries, including Node.js, Babel, TypeScript, React, Angular, and Vue. Key features include parallel test execution in isolated processes for performance, snapshot testing for large objects, and a comprehensive built-in API (e.g., it and expect).
  2. Debug Jest configuration and open handles

    Use --debug to print debugging information about the current Jest configuration. To identify resources preventing Jest from exiting cleanly, use --detectOpenHandles. Note that --detectOpenHandles implies --runInBand (serial execution) and has a significant performance penalty.
    # Debug config
    jest --debug
    
    # Track open handles
    jest --detectOpenHandles
  3. Understand JSDOM upgrade changes in Jest 29

    The jest-environment-jsdom package has been upgraded from jsdom v19 to v20. This update provides native support for crypto.getRandomValues(), allowing packages like uuid and nanoid to work without additional polyfills. Note that if you use jest-environment-jsdom, TypeScript version 4.5 or higher is required.
  4. Understand JSDOM upgrades in Jest 29

    The jest-environment-jsdom package has been upgraded from jsdom v19 to v20. This upgrade provides native support for crypto.getRandomValues(), allowing packages like uuid and nanoid to work without additional polyfills. Note that if you use jest-environment-jsdom, the minimum required TypeScript version is 4.5.
  5. Resolve React 16+ warnings when mocking components in snapshots

    When mocking modules in React 16+ (e.g., using jest.mock), you may see warnings about uppercase HTML tags. This happens because the mocked module fails React's element type checks. Choose one of the following solutions:

    1. Render as text: Mock the component as a function returning a string.
    2. Render as a custom element: Mock the component as a function returning a lowercase tag with a dash (e.g., <mock-widget />).
    3. Use react-test-renderer: This renderer ignores element type checks.
    4. Disable warnings: Mock the warning library in the Jest setup file.
    // Option 1: Render as text
    jest.mock('./SomeComponent', () => () => 'SomeComponent');
    
    // Option 2: Render as custom element
    jest.mock('./Widget', () => () => <mock-widget />);
    
    // Option 4: Disable warnings
    jest.mock('fbjs/lib/warning', () => require('fbjs/lib/emptyFunction'));
  6. Generate a basic Jest configuration file

    You can interactively generate a basic Jest configuration file by running the init command, which will prompt you with a few questions about your project.
    npm init jest@latest
  7. Use integrated Babel support in Jest 11.0

    In Jest 11.0, babel-jest has been adopted into the modularized Jest repository and is now seamlessly integrated into the core product, simplifying the setup process for projects requiring Babel transformation.
  8. 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 execution. This is used to assert call counts, arguments, contexts, and instantiation.
    // Check call count
    expect(someMockFunction.mock.calls).toHaveLength(1);
    
    // Check specific arguments: [callIndex][argumentIndex]
    expect(someMockFunction.mock.calls[0][0]).toBe('first arg');
    
    // Check return value of a specific call
    expect(someMockFunction.mock.results[0].value).toBe('return value');
    
    // Check the 'this' context of a call
    expect(someMockFunction.mock.contexts[0]).toBe(element);
    
    // Check how many times the function was called with 'new'
    expect(someMockFunction.mock.instances.length).toBe(2);
    
    // Get the first argument of the most recent call
    expect(someMockFunction.mock.lastCall[0]).toBe('test');
  9. Assert mock function calls using custom matchers

    Jest provides built-in matcher functions to simplify assertions about how mock functions were called. These matchers provide a concise alternative to manually inspecting the .mock property.
    // The mock function was called at least once
    expect(mockFunc).toHaveBeenCalled();
    
    // The mock function was called at least once with the specified args
    expect(mockFunc).toHaveBeenCalledWith(arg1, arg2);
    
    // The last call to the mock function was called with the specified args
    expect(mockFunc).toHaveBeenLastCalledWith(arg1, arg2);
    
    // All calls and the name of the mock is written as a snapshot
    expect(mockFunc).toMatchSnapshot();
  10. Debug Jest configuration and memory leaks

    Use --debug to print debugging information about your Jest configuration. To debug memory leaks, use --logHeapUsage, which logs heap usage after every test; for best results, combine this with --runInBand and the Node.js --expose-gc flag.
  11. 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 execution. This is used to assert call counts, arguments, return values, and context.
    // Check call count
    expect(someMockFunction.mock.calls).toHaveLength(1);
    
    // Check specific arguments
    expect(someMockFunction.mock.calls[0][0]).toBe('first arg');
    
    // Check return value
    expect(someMockFunction.mock.results[0].value).toBe('return value');
    
    // Check 'this' context
    expect(someMockFunction.mock.contexts[0]).toBe(element);
    
    // Check constructor instantiations
    expect(someMockFunction.mock.instances.length).toBe(2);
    
    // Check the last call arguments
    expect(someMockFunction.mock.lastCall[0]).toBe('test');
  12. Assert mock function calls using custom matchers

    Jest provides built-in matcher functions to simplify assertions about how mock functions were invoked. These matchers act as syntactic sugar for inspecting the .mock property.
    // The mock function was called at least once
    expect(mockFunc).toHaveBeenCalled();
    
    // The mock function was called at least once with the specified args
    expect(mockFunc).toHaveBeenCalledWith(arg1, arg2);
    
    // The last call to the mock function was called with the specified args
    expect(mockFunc).toHaveBeenLastCalledWith(arg1, arg2);
    
    // All calls and the name of the mock is written as a snapshot
    expect(mockFunc).toMatchSnapshot();