Skip to content

Commit d390eb5

Browse files
authored
fix(mocker): fix mock transform with class (#9421)
1 parent f7ffacf commit d390eb5

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

packages/mocker/src/node/esmWalker.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,17 @@ export function esmWalker(
157157
identifiers.push([node, parentStack.slice(0)])
158158
}
159159
}
160+
else if (node.type === 'ClassDeclaration' && node.id) {
161+
// A class declaration name could shadow an import, so add its name to the parent scope
162+
const parentScope = findParentScope(parentStack)
163+
if (parentScope) {
164+
setScope(parentScope, node.id.name)
165+
}
166+
}
167+
else if (node.type === 'ClassExpression' && node.id) {
168+
// A class expression name could shadow an import, so add its name to the scope
169+
setScope(node, node.id.name)
170+
}
160171
else if (isFunctionNode(node)) {
161172
// If it is a function declaration, it could be shadowing an import
162173
// Add its name to the scope so it won't get replaced

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,6 +1117,52 @@ const Baz = class extends Foo {}
11171117
`)
11181118
})
11191119

1120+
test('classDeclaration shadowing import', () => {
1121+
const input = `\
1122+
import { Bar } from "./repro.js"
1123+
{
1124+
class Bar {
1125+
test() {}
1126+
}
1127+
const Zoo = class Zoo extends Bar {}
1128+
}
1129+
`
1130+
expect(hoistSimpleCodeWithoutMocks(input)).toMatchInlineSnapshot(`
1131+
"vi.mock('faker');
1132+
const __vi_import_0__ = await import("./repro.js");
1133+
import {vi} from "vitest";
1134+
1135+
{
1136+
class Bar {
1137+
test() {}
1138+
}
1139+
const Zoo = class Zoo extends Bar {}
1140+
}"
1141+
`)
1142+
})
1143+
1144+
test('classExpression name shadowing import', () => {
1145+
const input = `\
1146+
import { Foo } from "./foo.js"
1147+
const Bar = class Foo {
1148+
static create() {
1149+
return new Foo()
1150+
}
1151+
}
1152+
`
1153+
expect(hoistSimpleCodeWithoutMocks(input)).toMatchInlineSnapshot(`
1154+
"vi.mock('faker');
1155+
const __vi_import_0__ = await import("./foo.js");
1156+
import {vi} from "vitest";
1157+
1158+
const Bar = class Foo {
1159+
static create() {
1160+
return new Foo()
1161+
}
1162+
}"
1163+
`)
1164+
})
1165+
11201166
test('import assertion attribute', () => {
11211167
expect(
11221168
hoistSimpleCodeWithoutMocks(`

0 commit comments

Comments
 (0)