close

no-restricted-jest-methods

Configuration

rslint.config.ts
import { defineConfig, jestPlugin } from '@rslint/core';

export default defineConfig([
  jestPlugin.configs.recommended,
  {
    rules: {
      'jest/no-restricted-jest-methods': 'error',
    },
  },
]);

Rule Details

Disallow specific jest methods. Use this rule to ban particular jest.* calls that your team prefers to avoid, such as spies, mocks, or timer helpers, and optionally provide custom messages explaining the preferred alternative.

Restrictions are matched against the first member of a jest call chain. For example, banning fn reports jest.fn() and jest["fn"](), but not bare jest or jest() without a method name.

By default, no jest methods are restricted.

Examples of incorrect code for this rule with the following configuration:

{
  "jest/no-restricted-jest-methods": [
    "error",
    {
      "advanceTimersByTime": null,
      "spyOn": "Don't use spies"
    }
  ]
}
jest.useFakeTimers();
it('calls the callback after 1 second via advanceTimersByTime', () => {
  // ...

  jest.advanceTimersByTime(1000);

  // ...
});

test('plays video', () => {
  const spy = jest.spyOn(video, 'play');

  // ...
});

Options

  • First argument (required to enable the rule): object whose keys are restricted jest method names and whose values are custom messages.
    • Keys are method names such as fn, mock, spyOn, or advanceTimersByTime.
    • Values are either a string (shown as the diagnostic message) or null (uses the default message: Use of `{method}` is disallowed).

Examples of incorrect code with { "mock": "Do not use mocks" }:

jest.mock();
jest['mock']();

Examples of incorrect code with { "fn": null }:

jest.fn();
jest['fn']();

Examples of incorrect code with { "advanceTimersByTime": null }:

import { jest } from '@jest/globals';

jest.advanceTimersByTime(1000);

Original Documentation