oxc-project/oxc · warning · OxcDiagnostic

Prefer `jest.mocked()` over `fn as jest.Mock`.

Error message

Prefer `jest.mocked()` over `fn as jest.Mock`.

What it means

This is oxlint's 'jest/prefer-jest-mocked' diagnostic, a TypeScript rule. It flags TSAsExpression and TSTypeAssertion nodes whose outermost parenthesized parent is an assignment target or variable initializer casting a function to jest.Mock (e.g. const f = myFn as jest.Mock or (f as jest.Mock) = ...). jest.mocked() preserves generics and parameter types of the original function, whereas a raw jest.Mock cast erases them, so the rule prefers the typed helper.

Source

Thrown at crates/oxc_linter/src/rules/jest/prefer_jest_mocked.rs:12

use oxc_ast::{
    AstKind,
    ast::{AssignmentTarget, TSAsExpression, TSType, TSTypeAssertion, TSTypeName, TSTypeReference},
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::{GetSpan, Span};

use crate::{AstNode, ast_util::outermost_paren_parent, context::LintContext, rule::Rule};

fn use_jest_mocked(span: Span) -> OxcDiagnostic {
    OxcDiagnostic::warn("Prefer `jest.mocked()` over `fn as jest.Mock`.")
        .with_help("Prefer `jest.mocked()`")
        .with_label(span)
}

#[derive(Debug, Default, Clone)]
pub struct PreferJestMocked;

declare_oxc_lint!(
    /// ### What it does
    ///
    /// When working with mocks of functions using Jest, it's recommended to use the
    /// `jest.mocked()` helper function to properly type the mocked functions. This rule
    /// enforces the use of `jest.mocked()` for better type safety and readability.
    ///
    /// Restricted types:
    /// - `jest.Mock`
    /// - `jest.MockedFunction`
    /// - `jest.MockedClass`

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Replace the cast with the typed helper: const mockedFn = jest.mocked(originalFn) — it infers the original signature.
  2. For whole modules, combine jest.mock('./mod') with jest.mocked: import { fn } from './mod'; jest.mock('./mod'); const mockedFn = jest.mocked(fn).
  3. If you need partial mocks, use jest.mocked(fn, { partial: true }) (Jest 28+) instead of a loose cast.
  4. Suppress rare unavoidable casts with // oxlint-disable-next-line jest/prefer-jest-mocked.

Example fix

// before
import { fetchUser } from './api';
jest.mock('./api');
const mockedFetchUser = fetchUser as jest.Mock;

// after
import { fetchUser } from './api';
jest.mock('./api');
const mockedFetchUser = jest.mocked(fetchUser);
Defensive patterns

Strategy: type-guard

Validate before calling

// list jest.Mock casts before enabling the rule
const { execSync } = require('node:child_process');
console.log(execSync("rg -n 'as\\s+jest\\.Mock|<jest\\.Mock' --glob '*.ts' --glob '*.tsx' tests/", { encoding: 'utf8' }));

Type guard

// prefer the typed helper; it infers the original signature
import { fetchUser } from './api';
jest.mock('./api');
const mockedFetchUser = jest.mocked(fetchUser); // type carries through
// jest.mocked returns jest.Mocked<typeof fetchUser> — no manual cast needed

Prevention

When it happens

Trigger: Enable the rule and lint TS code containing 'x as jest.Mock' or '<jest.Mock>x' (including nested reference forms like jest.Mock<...> or jest.MockedFunction) where the cast expression feeds a variable declaration or assignment. The diagnostic span covers the cast; the help is 'Prefer `jest.mocked()`'.

Common situations: The most copied Stack Overflow pattern for typing mocked modules is const mockedFn = mockedThing as jest.Mock. After upgrading typing setups or enabling the jest plugin's stricter rules, codebases find dozens of these. It also appears when casting whole modules: import { thing } from './mod'; const mock = thing as jest.Mock.

Related errors


AI-assisted analysis of oxc-project/oxc@e1e7af627c (2026-08-20). Data as JSON: /api/errors/d09078e59185db95. Report an issue: GitHub.