Jest

Shortening Output

$ DEBUG_PRINT_LIMIT=0 jest --noStackTrace

Mock Functions

https://jestjs.io/docs/en/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
jest.fn()

.mockReturnValue()
.mockReturnValueOnce()
.mockResolvedValue()
  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:

.mockReturnValue()
.mockReturnValueOnce()
.mockResolvedValue()
.mockImplementation(fn)
.mockReturnThis() - for chaining

Helpful for output:

.mockName('thingName')

Matching on mocks

[.not]
.toBeCalled()
.toBeCalledWith()

Mocking Modules

https://jestjs.io/docs/mock-functions#mocking-modules

import something from 'path/to/module';

jest.mock('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

https://krasimirtsonev.com/blog/article/jest-mock-console-methods

// silencing:

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

// asserting
expect(warn).toHaveBeenCalledWith("HI")

// reverting
warn.mockReset();

Table-Based Tests

test.each

test.each`
  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.

Options:

  • 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

Timeout