Skip to content

test(cli): qr-cli.test.ts fails with ReferenceError due to vitest mock hoisting #73177

@DoncicX

Description

@DoncicX

Summary

src/cli/qr-cli.test.ts fails deterministically with a ReferenceError: Cannot access '__vi_import_2__' before initialization when the module import chain includes ../logging/subsystem.js.

This is a pre-existing vitest mock hoisting bug that becomes exposed when any file in the same import graph adds a new dependency on logging/subsystem.

Error

Error: [vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock
Caused by: ReferenceError: Cannot access '__vi_import_2__' before initialization
 ❯ src/cli/qr-cli.test.ts:21:3
 ❯ src/logging/subsystem.ts:5:1
 ❯ src/security/windows-acl.ts:4:1
 ❯ src/security/audit-fs.ts:2:1
 ❯ src/secrets/resolve.ts:13:1
 ❯ src/gateway/auth-config-utils.ts:4:1
 ❯ src/pairing/setup-code.ts:5:1
 ❯ src/cli/qr-cli.test.ts:3:1

Root cause

qr-cli.test.ts defines top-level variables (e.g. runtime from createCliRuntimeCapture()) and then references them inside vi.mock() factory functions.

Because vi.mock() is hoisted to the top of the file by vitest, those top-level variables have not yet been initialized when the factory runs. Normally this test passes because the import chain during initialization does not trigger the mock factory early. However, any change that introduces a new module dependency into the import graph (such as adding import { createSubsystemLogger } from "../logging/subsystem.js" to windows-acl.ts) alters the initialization order and causes the hoisted mock factory to execute before its captured variables are ready.

Reproduction

  1. Add import { createSubsystemLogger } from "../logging/subsystem.js" to src/security/windows-acl.ts
  2. Run pnpm vitest run src/cli/qr-cli.test.ts
  3. Observe the __vi_import_2__ initialization error

Suggested fix

Refactor qr-cli.test.ts so that variables referenced inside vi.mock() factories are created via vi.hoisted() instead of top-level const declarations, ensuring they are available when the mock factory executes.

Affected CI jobs

  • checks-node-agentic-commands
  • checks-node-core (indirectly, when the test suite includes this file)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions