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
11 changes: 11 additions & 0 deletions packages/mocker/src/node/esmWalker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,17 @@ export function esmWalker(
identifiers.push([node, parentStack.slice(0)])
}
}
else if (node.type === 'ClassDeclaration' && node.id) {
// A class declaration name could shadow an import, so add its name to the parent scope
const parentScope = findParentScope(parentStack)
if (parentScope) {
setScope(parentScope, node.id.name)
}
}
else if (node.type === 'ClassExpression' && node.id) {
// A class expression name could shadow an import, so add its name to the scope
setScope(node, node.id.name)
}
Comment on lines +160 to +170
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

else if (isFunctionNode(node)) {
// If it is a function declaration, it could be shadowing an import
// Add its name to the scope so it won't get replaced
Expand Down
46 changes: 46 additions & 0 deletions test/core/test/injector-mock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1117,6 +1117,52 @@ const Baz = class extends Foo {}
`)
})

test('classDeclaration shadowing import', () => {
const input = `\
import { Bar } from "./repro.js"
{
class Bar {
test() {}
}
const Zoo = class Zoo extends Bar {}
}
`
expect(hoistSimpleCodeWithoutMocks(input)).toMatchInlineSnapshot(`
"vi.mock('faker');
const __vi_import_0__ = await import("./repro.js");
import {vi} from "vitest";
{
class Bar {
test() {}
}
const Zoo = class Zoo extends Bar {}
Comment on lines +1136 to +1139
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without fix, this becomes:

class Bar {
  test() {}
}
const Zoo = class Zoo extends __vi_import_0__.Bar {}

}"
`)
})

test('classExpression name shadowing import', () => {
const input = `\
import { Foo } from "./foo.js"
const Bar = class Foo {
static create() {
return new Foo()
}
}
`
expect(hoistSimpleCodeWithoutMocks(input)).toMatchInlineSnapshot(`
"vi.mock('faker');
const __vi_import_0__ = await import("./foo.js");
import {vi} from "vitest";
const Bar = class Foo {
static create() {
return new Foo()
}
}"
Comment on lines +1158 to +1162
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without the fix, this becomes

const Bar = class Foo {
  static create() {
    return new __vi_import_0__.Foo()
  }
}

`)
})

test('import assertion attribute', () => {
expect(
hoistSimpleCodeWithoutMocks(`
Expand Down
Loading