Shortening Output

$ DEBUG_PRINT_LIMIT=0 jest --noStackTrace

Mock Functions

There are two ways to mock functions: Either by:

  1. creating a mock function to use in test code, or
  2. writing a manual mock to override a module dependency.

  1. Using a mock function - It’s standalone and can be passed around

  1. Mocking modules
import thing from 'thing'; // first do a real import of the whole module
jest.mock('thing'); // then mock it
thing.function.mockReturnValue(); // then properties on it are mocks and can be interacted with

What you can do with a mock:

.mockReturnThis() - for chaining

Helpful for output:


Matching on mocks


Mocking Modules

import something from 'path/to/module';

jest.mock('path/to/module', () => ({
  namedExport: 'value',

ES6 Default Export

jest.mock('path/to/module', () => ({
  __esModule: true,
  default: 'value',

Shared Mocks

  • jest.clearAllMocks() - clears out the calls and results
  • jest.resetAllMocks() - clear + remove mocked return values
  • jest.restoreAllMocks() - reset + restore original non-mocked functions

Mocking Console

// silencing:

const warn = jest.spyOn(console, "warn").mockImplementation(() => {});

// asserting

// reverting

Table-Based Tests


  a    | b    | expected
  ${1} | ${1} | ${2}
  ${1} | ${2} | ${3}
  ${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
  expect(a + b).toBe(expected);

SyntaxError: Cannot use import statement outside a module

This can occur when an NPM dependency is shipped as ES6. Jest has not historically worked with ESM modules.


  • Use native Jest ESM support. It is experimental, and it hasn’t fixed the issue I was experiencing; unclear why. Could just be a misconfigured third-party package.
  • transformIgnorePatterns - this config specifies what to ignore for Babel transformation. By default everything in node_modules is ignored. To change that, specify that everything in node_modules except certain subdirectories can be ignored: transformIgnorePatterns: ["node_modules/(?!@mui)/(?!x-charts)"],

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory


  • Per-test: it(name, testFn, timeout)