{"record":{"id":"d09078e59185db95","repo":"oxc-project/oxc","slug":"prefer-jest-mocked-over-fn-as-jest-mock","errorCode":null,"errorMessage":"Prefer `jest.mocked()` over `fn as jest.Mock`.","messagePattern":"Prefer `jest\\.mocked\\(\\)` over `fn as jest\\.Mock`\\.","errorType":"validation","errorClass":"OxcDiagnostic","httpStatus":null,"severity":"warning","filePath":"crates/oxc_linter/src/rules/jest/prefer_jest_mocked.rs","lineNumber":12,"sourceCode":"use oxc_ast::{\n    AstKind,\n    ast::{AssignmentTarget, TSAsExpression, TSType, TSTypeAssertion, TSTypeName, TSTypeReference},\n};\nuse oxc_diagnostics::OxcDiagnostic;\nuse oxc_macros::declare_oxc_lint;\nuse oxc_span::{GetSpan, Span};\n\nuse crate::{AstNode, ast_util::outermost_paren_parent, context::LintContext, rule::Rule};\n\nfn use_jest_mocked(span: Span) -> OxcDiagnostic {\n    OxcDiagnostic::warn(\"Prefer `jest.mocked()` over `fn as jest.Mock`.\")\n        .with_help(\"Prefer `jest.mocked()`\")\n        .with_label(span)\n}\n\n#[derive(Debug, Default, Clone)]\npub struct PreferJestMocked;\n\ndeclare_oxc_lint!(\n    /// ### What it does\n    ///\n    /// When working with mocks of functions using Jest, it's recommended to use the\n    /// `jest.mocked()` helper function to properly type the mocked functions. This rule\n    /// enforces the use of `jest.mocked()` for better type safety and readability.\n    ///\n    /// Restricted types:\n    /// - `jest.Mock`\n    /// - `jest.MockedFunction`\n    /// - `jest.MockedClass`","sourceCodeStart":1,"sourceCodeEnd":30,"githubUrl":"https://github.com/oxc-project/oxc/blob/e1e7af627c8843ab64044ed466b128fcc21a035b/crates/oxc_linter/src/rules/jest/prefer_jest_mocked.rs#L1-L30","documentation":"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.","triggerScenarios":"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()`'.","commonSituations":"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.","solutions":["Replace the cast with the typed helper: const mockedFn = jest.mocked(originalFn) — it infers the original signature.","For whole modules, combine jest.mock('./mod') with jest.mocked: import { fn } from './mod'; jest.mock('./mod'); const mockedFn = jest.mocked(fn).","If you need partial mocks, use jest.mocked(fn, { partial: true }) (Jest 28+) instead of a loose cast.","Suppress rare unavoidable casts with // oxlint-disable-next-line jest/prefer-jest-mocked."],"exampleFix":"// before\nimport { fetchUser } from './api';\njest.mock('./api');\nconst mockedFetchUser = fetchUser as jest.Mock;\n\n// after\nimport { fetchUser } from './api';\njest.mock('./api');\nconst mockedFetchUser = jest.mocked(fetchUser);","handlingStrategy":"type-guard","validationCode":"// list jest.Mock casts before enabling the rule\nconst { execSync } = require('node:child_process');\nconsole.log(execSync(\"rg -n 'as\\\\s+jest\\\\.Mock|<jest\\\\.Mock' --glob '*.ts' --glob '*.tsx' tests/\", { encoding: 'utf8' }));","typeGuard":"// prefer the typed helper; it infers the original signature\nimport { fetchUser } from './api';\njest.mock('./api');\nconst mockedFetchUser = jest.mocked(fetchUser); // type carries through\n// jest.mocked returns jest.Mocked<typeof fetchUser> — no manual cast needed","tryCatchPattern":null,"preventionTips":["Ban 'as jest.Mock' in TS code review; require jest.mocked(fn) instead.","For partial mocks use jest.mocked(fn, { partial: true }) rather than widening casts.","Let the compiler check mock types by never casting to the bare jest.Mock interface."],"tags":["lint","jest","typescript","mocking","type-cast","oxlint"],"backgroundTag":"jest-mocked-type-cast","analyzedSha":"e1e7af627c8843ab64044ed466b128fcc21a035b","analyzedAt":"2026-08-20T07:01:07.079Z","contentChangedAt":"2026-08-20T07:01:07.079Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}