diff --git a/config/resolvesnapshotpath.md b/config/resolvesnapshotpath.md index 981ff412..0e1f1a24 100644 --- a/config/resolvesnapshotpath.md +++ b/config/resolvesnapshotpath.md @@ -2,7 +2,7 @@ title: resolveSnapshotPath | Config outline: deep --- - + # resolveSnapshotPath - **Type**: `(testPath: string, snapExtension: string, context: { config: SerializedConfig }) => string` @@ -19,3 +19,23 @@ export default defineConfig({ }, }) ``` + +You can also use the `context` parameter to access the project's serialized config. This is useful when you have multiple [projects](/guide/projects) and want to store snapshots in different locations based on the project name: + +```ts +import { basename, dirname, join } from 'node:path' +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + resolveSnapshotPath(testPath, snapExtension, context) { + return join( + dirname(testPath), + '__snapshots__', + context.config.name ?? 'default', + basename(testPath) + snapExtension, + ) + }, + }, +}) +``` diff --git a/guide/test-context.md b/guide/test-context.md index e8268c5b..2cd7e219 100644 --- a/guide/test-context.md +++ b/guide/test-context.md @@ -405,10 +405,16 @@ const test = baseTest.extend({ ], }) ``` + + +::: warning +The built-in [`task`](#task) test context is **not available** in file-scoped or worker-scoped fixtures. These fixtures receive a different context object (file or worker context) that does not include test-specific properties like `task`. + +If you need access to file-level metadata like the file path, use `expect.getState().testPath` instead. +::: `worker` 作用域将为每个工作线程运行一次夹具。运行的工作线程数量取决于各种因素。默认情况下,每个文件在单独的工作线程中运行,因此 `file` 和 `worker` 作用域的工作方式相同。 - However, if you disable [isolation](/config/#isolate), then the number of workers is limited by the [`maxWorkers`](/config/#maxworkers) configuration. 请注意,在 `vmThreads` 或 `vmForks` 中运行测试时,指定 `scope: 'worker'` 的工作方式与 `scope: 'file'` 相同。这个限制存在是因为每个测试文件都有自己的 VM 上下文,所以如果 Vitest 只初始化一次,一个上下文可能会泄漏到另一个上下文中,并创建许多引用不一致的问题(例如,同一个类的实例会引用不同的构造函数)。