Skip to content

Browser mode: vi.mock of a non-JS module (svg, json, ?query assets) is ignored with import map mocks (5.1.0) #11952

Open

Description

@mohammad-naji7

Describe the bug

Since 5.1.0 serves browser mocks through an import map (#11534), vi.mock of any module that Vite imports with an explicit ?import query is silently ignored: the real module loads and no error is reported. That is every import that is not a JS or CSS request: .svg, .png, .json, ./icon.svg?component, etc.

resolveMockImportMap (packages/browser/src/node/mocks.ts) builds the key from module.url (/icon.svg?component, /plain.svg, /data.json), adding only v= and t=. Vite's import analysis emits /icon.svg?import&component, /plain.svg?import, /data.json?import (isExplicitImportRequired → injectQuery(url, 'import'), which puts import first), so the key never matches. With browser.importMapMocks: false the same test passes.

Suggested fix: apply Vite's rule when building the key. If the URL is not a JS/CSS request, inject import the way injectQuery does (/a.svg?component → /a.svg?import&component). Writing the mock specifier as ./icon.svg?import&component makes the SVG cases pass, which confirms the key mismatch. JSON then resolves to undefined, so the manual-mock shim for JSON may need a look too.

Reproduction

https://github.com/mohammad-naji7/vitest-import-map-mock-repro

npm install && npx playwright install chromium, then:

  • npm test: 1 passed, 3 failed (the svg, svg?component and json mocks are ignored)
  • npm run test:no-import-map: 4 passed, with browser.importMapMocks: false

System Info

macOS 27.2, Apple M3 Pro
Node 26.10.0, npm 11.19.1
vitest 5.1.0, @vitest/browser 5.1.0, @vitest/browser-playwright 5.1.0, vite 8.3.8, playwright 1.61.1 (Chromium, headless)

Used Package Manager

npm

Validations

Activity

  1. mohammad-naji7 commented on Nov 12, 2026

    @mohammad-naji7
    Author

    I have a fix with a regression test ready: main...mohammad-naji7:vitest:fix/browser-import-map-mock-non-js

    resolveMockImportMap now adds import to the key the way Vite does (only for non-JS/CSS URLs, at the front of the query), and the new mocked-non-js.test.ts fixture mocks an ?raw svg, a plain svg and a json file. It fails without the change and passes with it in the importMapMocks: true run of specs/mocking.test.ts.

    Happy to open a PR if this gets the approved label.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions