fix(mocker): skip hoist transform without ast mock calls (#10410) · vitest-dev/vitest@0468e15 (original) (raw)

Original file line number Diff line number Diff line change
@@ -248,6 +248,7 @@ export function hoistMocks(
248 248
249 249 const usedUtilityExports = new Set<string>()
250 250 let hasImportMetaVitest = false
251 +let hasMockApiCall = false
251 252
252 253 esmWalker(ast, {
253 254 onImportMeta(node) {
@@ -310,6 +311,7 @@ export function hoistMocks(
310 311 usedUtilityExports.add(node.callee.object.name)
311 312
312 313 if (hoistableMockMethodNames.includes(methodName)) {
314 +hasMockApiCall = true
313 315 const method = `${node.callee.object.name}.${methodName}`
314 316 assertNotDefaultExport(
315 317 node,
@@ -356,6 +358,7 @@ export function hoistMocks(
356 358 // vi.doMock(import('./path')) -> vi.doMock('./path')
357 359 // vi.doMock(await import('./path')) -> vi.doMock('./path')
358 360 else if (dynamicImportMockMethodNames.includes(methodName)) {
361 +hasMockApiCall = true
359 362 const moduleInfo = node.arguments[0] as Positioned<Expression>
360 363 let source: Positioned<Expression> | null = null
361 364 if (moduleInfo.type === 'ImportExpression') {
@@ -377,6 +380,7 @@ export function hoistMocks(
377 380 }
378 381
379 382 if (hoistedMethodNames.includes(methodName)) {
383 +hasMockApiCall = true
380 384 assertNotDefaultExport(
381 385 node,
382 386 'Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.',
@@ -406,6 +410,10 @@ export function hoistMocks(
406 410 },
407 411 })
408 412
413 +if (!hasMockApiCall) {
414 +return
415 +}
416 +
409 417 function getNodeName(node: CallExpression) {
410 418 const callee = node.callee |
411 419 if (
Original file line number Diff line number Diff line change
@@ -774,7 +774,7 @@ add(4);
774 774 del = () => __vi_import_0__.del()
775 775 call = __vi_import_0__.call(4)
776 776 }
777 -
777 +
778 778 __vi_import_0__.remove(2);
779 779 __vi_import_0__.add(4);"
780 780 `)
@@ -1742,3 +1742,18 @@ if (import.meta.vitest) {
1742 1742 expect(warn).not.toHaveBeenCalled()
1743 1743 })
1744 1744 })
1745 +
1746 +test('does not transform when hoistable API only appears in comments', () => {
1747 +expect(hoistSimpleCode(`
1748 +import { lib } from 'lib'
1749 +// vi.mock('lib')
1750 +console.log(lib)
1751 + `)).toMatchInlineSnapshot(`undefined`)
1752 +})
1753 +
1754 +test('does not transform when hoistable API only appears in strings', () => {
1755 +expect(hoistSimpleCode(`
1756 +import { lib } from 'lib'
1757 +console.log("vi.mock('lib')", lib)
1758 + `)).toMatchInlineSnapshot(`undefined`)
1759 +})