Skip to content

Commit

Permalink
feat(dev): rename the modulePatterns option to moduleDirectories and …
Browse files Browse the repository at this point in the history
…turn it into a list of strings or RegExp
  • Loading branch information
fooddilsn committed May 10, 2023
1 parent 8a21a2d commit d5c11d0
Show file tree
Hide file tree
Showing 6 changed files with 21 additions and 14 deletions.
2 changes: 1 addition & 1 deletion docs/api/vi.md
Expand Up @@ -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:

Expand Down
12 changes: 7 additions & 5 deletions docs/config/index.md
Expand Up @@ -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')],
},
})
```
2 changes: 1 addition & 1 deletion packages/vitest/src/defaults.ts
Expand Up @@ -94,7 +94,7 @@ const config = {
exclude: defaultExclude,
},
slowTestThreshold: 300,
modulePatterns: ['**/node_modules/**'],
moduleDirectories: ['node_modules'],
}

export const configDefaults: Required<Pick<UserConfig, keyof typeof config>> = Object.freeze(config)
4 changes: 2 additions & 2 deletions packages/vitest/src/runtime/execute.ts
Expand Up @@ -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) {
Expand Down Expand Up @@ -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,
})
Expand Down
13 changes: 9 additions & 4 deletions packages/vitest/src/runtime/mocker.ts
Expand Up @@ -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'
Expand Down Expand Up @@ -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) {
Expand All @@ -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'
}
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/types/config.ts
Expand Up @@ -586,7 +586,7 @@ export interface InlineConfig {
*
* @default ['**\/node_modules\/**']
*/
modulePatterns?: string[]
moduleDirectories?: (string | RegExp)[]
}

export interface TypecheckConfig {
Expand Down

0 comments on commit d5c11d0

Please sign in to comment.