Skip to content

Commit 773b10e

Browse files
authored
fix: fix already hoisted mock (#7815)
1 parent 29084f1 commit 773b10e

File tree

4 files changed

+36
-3
lines changed

4 files changed

+36
-3
lines changed

eslint.config.js

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export default antfu(
1515
'**/*.d.ts',
1616
'**/*.timestamp-*',
1717
'test/core/src/self',
18+
'test/core/test/mocking/already-hoisted.test.ts',
1819
'test/cache/cache/.vitest-base/results.json',
1920
'test/core/src/wasm/wasm-bindgen-no-cyclic',
2021
'test/workspaces/results.json',

packages/mocker/src/node/hoistMocksPlugin.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -498,11 +498,11 @@ export function hoistMocks(
498498
// hoist vi.mock/vi.hoisted
499499
for (const node of hoistedNodes) {
500500
const end = getNodeTail(code, node)
501-
if (hoistIndex === end) {
501+
// don't hoist into itself if it's already at the top
502+
if (hoistIndex === end || hoistIndex === node.start) {
502503
hoistIndex = end
503504
}
504-
// don't hoist into itself if it's already at the top
505-
else if (hoistIndex !== node.start) {
505+
else {
506506
s.move(node.start, end, hoistIndex)
507507
}
508508
}

test/core/test/injector-mock.test.ts

+23
Original file line numberDiff line numberDiff line change
@@ -1273,6 +1273,29 @@ test('test', async () => {
12731273
`)
12741274
})
12751275

1276+
test('vi.mock already hoisted at the top', () => {
1277+
expect(
1278+
hoistSimpleCode(`\
1279+
vi.mock('node:path', () => ({ mocked: true }));
1280+
1281+
import { test, vi } from 'vitest';
1282+
1283+
import * as path from 'node:path';
1284+
1285+
console.log(path.mocked);
1286+
`),
1287+
).toMatchInlineSnapshot(`
1288+
"vi.mock('node:path', () => ({ mocked: true }));
1289+
const __vi_import_0__ = await import("node:path");
1290+
1291+
import { test, vi } from 'vitest';
1292+
1293+
1294+
1295+
console.log(__vi_import_0__.mocked);"
1296+
`)
1297+
})
1298+
12761299
test('correctly hoists when import.meta is used', () => {
12771300
expect(hoistSimpleCode(`
12781301
import { calc } from './calc'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
vi.mock('node:path', () => ({ mocked: true }))
2+
3+
import { expect, test, vi } from 'vitest'
4+
5+
import * as path from 'node:path'
6+
7+
test('already hoisted', () => {
8+
expect(path).toHaveProperty('mocked', true)
9+
})

0 commit comments

Comments
 (0)