Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/vitest/src/runtime/moduleRunner/moduleMocker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ export class VitestMocker extends BareModuleMocker {
mock: MockedModule,
): Promise<any> {
return this._otel.$('vitest.mocker.evaluate', async (span) => {
const mockId = this.getMockPath(evaluatedNode.id)
const mockId = this.getMockPath(mock.id)

span.setAttributes({
'vitest.module.id': mockId,
Expand Down
11 changes: 6 additions & 5 deletions packages/vitest/src/runtime/moduleRunner/moduleRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,14 +178,15 @@ export class VitestModuleRunner extends viteModuleRunner.ModuleRunner implements
}

let mocked: any
if (mod.meta && 'mockedModule' in mod.meta) {
const mockId = this.mocker.getMockPath(mod.id)
const currentMock = this.mocker.getDependencyMock(mod.id)
const meta = mod.meta
if (meta && 'mockedModule' in meta && typeof meta.mockedModule === 'string') {
const mockId = this.mocker.getMockPath(meta.mockedModule)
const currentMock = this.mocker.getDependencyMock(meta.mockedModule)
// bypass mock and force "importActual" behavior when:
// - mock was removed by doUnmock (stale mockedModule in meta)
if (!currentMock) {
const node = await this.fetchModule(injectQuery(url, '_vitest_original'))
return this._cachedRequest(node.url, node, callstack, metadata)
return this.cachedRequest(node.url, node, callstack, metadata, true)
}
// - self-import: mock factory/file is importing the module it's mocking
const isSelfImport =
Expand All @@ -195,7 +196,7 @@ export class VitestModuleRunner extends viteModuleRunner.ModuleRunner implements
('redirect' in currentMock && callstack.includes(currentMock.redirect))
if (isSelfImport) {
const node = await this.fetchModule(injectQuery(url, '_vitest_original'))
return this._cachedRequest(node.url, node, callstack, metadata)
return this.cachedRequest(node.url, node, callstack, metadata, true)
}
// mocked metadata comes from a manual or redirect mock and has no code to automock
const isAutoMock = currentMock.type === 'automock' || currentMock.type === 'autospy'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { getCachedVitestImport } from './cachedResolver'
import { unwrapId, VitestModuleEvaluator } from './moduleEvaluator'
import { VitestMocker } from './moduleMocker'
import { VitestModuleRunner } from './moduleRunner'
import { removeQuery } from './utils'
import { injectQuery, removeQuery } from './utils'

const { readFileSync } = fs

Expand Down Expand Up @@ -193,11 +193,13 @@ export function startVitestModuleRunner(options: ContextModuleRunnerOptions): Vi
return {
code: '',
file: null,
id: resolvedMock.id,
// each fetch replaces the meta of its node, so the placeholder needs its own id,
// the query keeps the file of the original module for the recorded dependencies
id: injectQuery(resolvedMock.id, '_vitest_mocked'),
url: resolvedMock.url,
invalidate: false,
// the module node outlives the test file, so it must not keep the mock factory alive
mockedModule: true,
mockedModule: resolvedMock.id,
}
}
}
Expand Down
38 changes: 38 additions & 0 deletions test/e2e/test/mocking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,44 @@ test('import scheduled by the factory gets the mock', async () => {
`)
})

test('importOriginal() gets the original while the mocked module is imported again', async () => {
const { stderr, testTree } = await runInlineTests({
'./basic.test.js': `
import { expect, test, vi } from 'vitest'

test('the mock keeps the original exports', async () => {
const roundsWithoutOriginal = []
// node:os resolves in the worker, so each round starts the second import one microtask later
for (let round = 0; round < 60; round++) {
vi.resetModules()
vi.doMock('node:os', async (importOriginal) => ({
...(await importOriginal()),
hostname: () => 'mocked',
}))
const first = import('node:os')
for (let tick = 0; tick < round; tick++) {
await null
}
const [os] = await Promise.all([first, import('node:os')])
if (!('platform' in os) || os.hostname() !== 'mocked') {
roundsWithoutOriginal.push(round)
}
}
expect(roundsWithoutOriginal).toEqual([])
})
`,
})

expect(stderr).toBe('')
expect(testTree()).toMatchInlineSnapshot(`
{
"basic.test.js": {
"the mock keeps the original exports": "passed",
},
}
`)
})

test('factory gets partial exports of a module that waits for the mock', async () => {
const { stderr, errorTree } = await runInlineTests({
'./dep.js': `export const value = 'original'`,
Expand Down
Loading