From d5c11d0d6d35c742b4b42ca83135b444834ce6e8 Mon Sep 17 00:00:00 2001 From: Alessandro Di Dio Date: Wed, 10 May 2023 18:39:46 +0200 Subject: [PATCH] feat(dev): rename the modulePatterns option to moduleDirectories and turn it into a list of strings or RegExp --- docs/api/vi.md | 2 +- docs/config/index.md | 12 +++++++----- packages/vitest/src/defaults.ts | 2 +- packages/vitest/src/runtime/execute.ts | 4 ++-- packages/vitest/src/runtime/mocker.ts | 13 +++++++++---- packages/vitest/src/types/config.ts | 2 +- 6 files changed, 21 insertions(+), 14 deletions(-) diff --git a/docs/api/vi.md b/docs/api/vi.md index a3c61e070e07..5de094097f52 100644 --- a/docs/api/vi.md +++ b/docs/api/vi.md @@ -234,7 +234,7 @@ import { vi } from 'vitest' ``` ::: - If there is a `__mocks__` folder alongside a file that you are mocking, and the factory is not provided, Vitest will try to find a file with the same name in the `__mocks__` subfolder and use it as an actual module. If you are mocking a dependency, Vitest will try to find a `__mocks__` folder in the [root](/config/#root) of the project (default is `process.cwd()`). + If there is a `__mocks__` folder alongside a file that you are mocking, and the factory is not provided, Vitest will try to find a file with the same name in the `__mocks__` subfolder and use it as an actual module. If you are mocking a dependency, Vitest will try to find a `__mocks__` folder in the [root](/config/#root) of the project (default is `process.cwd()`). You can tell Vitest where the dependencies are located through the [moduleDirectories](/config/#moduleDirectories) config option. For example, you have this file structure: diff --git a/docs/config/index.md b/docs/config/index.md index bf829135dcb6..b94a973f88d6 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -1411,19 +1411,21 @@ Stop test execution when given number of tests have failed. By default Vitest will run all of your test cases even if some of them fail. This may not be desired for CI builds where you are only interested in 100% successful builds and would like to stop test execution as early as possible when test failures occur. The `bail` option can be used to speed up CI runs by preventing it from running more tests when failures have occured. -### modulePatterns +### moduleDirectories -- **Type**: `string[]` -- **Default**: `['**/node_modules/**']` +- **Type:** `(string | RegExp)[]` +- **Default**: `[node_modules]` + +A list of directories that should be treated as module directories. This config option affects the behavior of [`vi.mock`](/api/vi#vi-mock): when no factory is provided and the path of what you are mocking matches one of the `moduleDirectories` values, Vitest will try to resolve the mock by looking for a `__mocks__` folder in the [root](/config/#root) of the project. -Glob pattern for file paths that should be treated as modules. Setting this option will override the default, if you wish to still search `**/node_modules/**` for packages include it along with any other options: +Setting this option will _override_ the default, if you wish to still search `node_modules` for packages include it along with any other options: ```ts import { defineConfig } from 'vitest/config' export default defineConfig({ test: { - modulePatterns: ['**/node_modules/**', path.resolve('../../packages/**')], + moduleDirectories: ['node_modules', path.resolve('../../packages')], }, }) ``` diff --git a/packages/vitest/src/defaults.ts b/packages/vitest/src/defaults.ts index 05b24004c2e0..b65bfc62ab5d 100644 --- a/packages/vitest/src/defaults.ts +++ b/packages/vitest/src/defaults.ts @@ -94,7 +94,7 @@ const config = { exclude: defaultExclude, }, slowTestThreshold: 300, - modulePatterns: ['**/node_modules/**'], + moduleDirectories: ['node_modules'], } export const configDefaults: Required> = Object.freeze(config) diff --git a/packages/vitest/src/runtime/execute.ts b/packages/vitest/src/runtime/execute.ts index 457ec995ec7b..f803c825dfc3 100644 --- a/packages/vitest/src/runtime/execute.ts +++ b/packages/vitest/src/runtime/execute.ts @@ -13,7 +13,7 @@ import { rpc } from './rpc' export interface ExecuteOptions extends ViteNodeRunnerOptions { mockMap: MockMap - modulePatterns: string[] + moduleDirectories: (string | RegExp)[] } export async function createVitestExecutor(options: ExecuteOptions) { @@ -71,7 +71,7 @@ export async function startViteNode(ctx: ContextRPC) { moduleCache, mockMap, interopDefault: config.deps.interopDefault, - modulePatterns: config.modulePatterns, + moduleDirectories: config.moduleDirectories, root: config.root, base: config.base, }) diff --git a/packages/vitest/src/runtime/mocker.ts b/packages/vitest/src/runtime/mocker.ts index 20d3031befee..7dca7a162f82 100644 --- a/packages/vitest/src/runtime/mocker.ts +++ b/packages/vitest/src/runtime/mocker.ts @@ -2,7 +2,6 @@ import { existsSync, readdirSync } from 'node:fs' import { basename, dirname, extname, isAbsolute, join, resolve } from 'pathe' import { getColors, getType } from '@vitest/utils' import { isNodeBuiltin } from 'vite-node/utils' -import mm from 'micromatch' import { getWorkerState } from '../utils/global' import { getAllMockableProperties } from '../utils/base' import { spyOn } from '../integrations/spy' @@ -59,8 +58,8 @@ export class VitestMocker { return this.executor.moduleCache } - private get modulePatterns() { - return this.executor.options.modulePatterns + private get moduleDirectories() { + return this.executor.options.moduleDirectories } private deleteCachedItem(id: string) { @@ -69,6 +68,12 @@ export class VitestMocker { this.moduleCache.delete(mockId) } + private isAModuleDirectory(path: string) { + return this.moduleDirectories.some(dir => + dir instanceof RegExp ? dir.test(path) : path.includes(`/${dir.replace(/(^\/?|\/?$)/g, '')}/`), + ) + } + public getSuiteFilepath(): string { return getWorkerState().filepath || 'global' } @@ -88,7 +93,7 @@ export class VitestMocker { const [id, fsPath] = await this.executor.resolveUrl(rawId, importer) // external is node_module or unresolved module // for example, some people mock "vscode" and don't have it installed - const external = (!isAbsolute(fsPath) || mm.isMatch(fsPath, this.modulePatterns, { dot: true })) ? rawId : null // { dot: true } is needed to match dotfolder like .pnpm + const external = (!isAbsolute(fsPath) || this.isAModuleDirectory(fsPath)) ? rawId : null return { id, diff --git a/packages/vitest/src/types/config.ts b/packages/vitest/src/types/config.ts index e7e4cc6290b9..2b28060f92fa 100644 --- a/packages/vitest/src/types/config.ts +++ b/packages/vitest/src/types/config.ts @@ -586,7 +586,7 @@ export interface InlineConfig { * * @default ['**\/node_modules\/**'] */ - modulePatterns?: string[] + moduleDirectories?: (string | RegExp)[] } export interface TypecheckConfig {