Skip to content

Commit

Permalink
fix(module): always append import when mocking (#701)
Browse files Browse the repository at this point in the history
  • Loading branch information
huang-julien authored Jan 17, 2024
1 parent d851f6e commit d045e17
Showing 1 changed file with 10 additions and 30 deletions.
40 changes: 10 additions & 30 deletions src/module/plugins/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import type { AstNode, TransformPluginContext, TransformResult } from 'rollup'
import MagicString from 'magic-string'
import type { Component } from '@nuxt/schema'
import type { Plugin } from 'vite'
import { normalize, resolve } from 'node:path'
import { createUnplugin } from 'unplugin'
import { resolvePath } from '@nuxt/kit'

export interface MockPluginContext {
imports: Import[]
Expand All @@ -33,16 +31,8 @@ export interface MockComponentInfo {
factory: string
}

export const createMockPlugin = (ctx: MockPluginContext) => createUnplugin(() => {
// path of the first vitest setup file to be ran
let resolvedFirstSetupFile: null | string = null

function transform (this: TransformPluginContext, code: string, id: string): TransformResult | Promise<TransformResult> {
const isFirstSetupFile = normalize(id) === resolvedFirstSetupFile
const shouldPrependMockHoist = resolvedFirstSetupFile
? isFirstSetupFile
: true

export const createMockPlugin = (ctx: MockPluginContext) => createUnplugin(() => {
function transform(this: TransformPluginContext, code: string, id: string): TransformResult | Promise<TransformResult> {
if (!HELPERS_NAME.some(n => code.includes(n))) return
if (id.includes('/node_modules/')) return

Expand All @@ -63,16 +53,16 @@ export const createMockPlugin = (ctx: MockPluginContext) => createUnplugin(() =>
const mocksImport: MockImportInfo[] = []
const mocksComponent: MockComponentInfo[] = []
const importPathsList: Set<string> = new Set()

walk(ast as any, {
enter: (node, parent) => {
// find existing vi import
if (isImportDeclaration(node)) {
if (node.source.value === 'vitest' && !hasViImport) {
const viImport = node.specifiers.find(
i =>
isImportSpecifier(i) && i.imported.name === 'vi'
)
i =>
isImportSpecifier(i) && i.imported.name === 'vi'
)
if (viImport) {
insertionPoint = endOf(node)
hasViImport = true
Expand Down Expand Up @@ -247,11 +237,9 @@ export const createMockPlugin = (ctx: MockPluginContext) => createUnplugin(() =>

// do an import to trick vite to keep it
// if not, the module won't be mocked
if (shouldPrependMockHoist) {
importPathsList.forEach(p => {
s.append(`\n import ${JSON.stringify(p)};`)
})
}
importPathsList.forEach(p => {
s.append(`\n import ${JSON.stringify(p)};`)
})

return {
code: s.toString(),
Expand All @@ -266,14 +254,6 @@ export const createMockPlugin = (ctx: MockPluginContext) => createUnplugin(() =>
transform,
// Place Vitest's mock plugin after all Nuxt plugins
async configResolved(config) {
const firstSetupFile = Array.isArray(config.test?.setupFiles)
? config.test!.setupFiles.find(p => !p.includes('runtime/entry'))
: config.test?.setupFiles

if (firstSetupFile) {
resolvedFirstSetupFile = await resolvePath(normalize(resolve(firstSetupFile)))
}

const plugins = (config.plugins || []) as Plugin[]

// `vite:mocks` was a typo in Vitest before v0.34.0
Expand All @@ -296,7 +276,7 @@ export const createMockPlugin = (ctx: MockPluginContext) => createUnplugin(() =>
})

// Polyfill Array.prototype.findLastIndex for legacy Node.js
function findLastIndex<T>(arr: T[], predicate: (item: T) => boolean) {
function findLastIndex<T> (arr: T[], predicate: (item: T) => boolean) {
for (let i = arr.length - 1; i >= 0; i--) {
if (predicate(arr[i])) return i
}
Expand Down

0 comments on commit d045e17

Please sign in to comment.