oxc-project/oxc · error · OxcDiagnostic

Hoisted API cannot be used in a runtime location in this fil

Error message

Hoisted API cannot be used in a runtime location in this file.

What it means

Emitted by the vitest/hoisted-apis-on-top rule when a hoisted vitest API (`vi.mock`, `vi.unmock`, `vi.doMock`, `vi.doUnmock`) is called in a runtime location — i.e. inside another function, hook, or non-top-level scope. These APIs are hoisted by vitest to the top of the file, so calling them from runtime code is invalid or misleading.

Source

Thrown at crates/oxc_linter/src/rules/vitest/hoisted_apis_on_top.rs:18

use oxc_ast::AstKind;
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::{GetSpan, Span};

use crate::{
    context::LintContext,
    fixer::RuleFixer,
    rule::Rule,
    utils::{
        JestFnKind, JestGeneralFnKind, KnownMemberExpressionProperty, PossibleJestNode,
        parse_general_jest_fn_call,
    },
};

fn hoisted_apis_on_top_diagnostic(span: Span) -> OxcDiagnostic {
    // TODO: Only mention the doMock alternative if the API in question is `vi.mock()`.
    OxcDiagnostic::warn("Hoisted API cannot be used in a runtime location in this file.")
        .with_help("Move this hoisted API to the top of the file to better reflect its behavior.\nYou may alternatively replace `vi.mock()` with `vi.doMock`, which is not hoisted.")
        .with_label(span)
}

const HOISTED_APIS: [&str; 3] = ["mock", "hoisted", "unmock"];

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

declare_oxc_lint!(
    /// ### What it does
    ///
    /// Requires [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) Vitest APIs
    /// (`vi.mock`, `vi.unmock`, and `vi.hoisted`) to appear at the top level of the file.
    ///
    /// ### Why is this bad?
    ///
    /// Vitest hoists certain APIs to the top of the file during transformation, so they always

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Move the `vi.mock()`/`vi.doMock()` call to the top level of the test file
  2. Use `vi.doMock` semantics deliberately, or restructure so mocking happens at module top level
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/oxc_linter/src/rules/vitest/hoisted_apis_on_top.rs:18 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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