From 07cd7320b5e882a63f80076aac8b6fc9c1b1da24 Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa Date: Mon, 28 Sep 2026 21:15:38 +0900 Subject: [PATCH] docs: document cwd behavior on projects (#11376) Co-authored-by: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Co-authored-by: Codex (GPT-6) --- docs/guide/common-errors.md | 25 +++++++++++++++++++++++++ docs/guide/projects.md | 2 ++ 2 files changed, 27 insertions(+) diff --git a/docs/guide/common-errors.md b/docs/guide/common-errors.md index d89c991c2..783aaa7f8 100644 --- a/docs/guide/common-errors.md +++ b/docs/guide/common-errors.md @@ -49,6 +49,31 @@ This error can happen when NodeJS's `fetch` is used with [`pool: 'threads'`](/co The default [`pool: 'forks'`](/config/pool#forks) does not have this issue. If you've explicitly set `pool: 'threads'`, switching back to `'forks'` or using [`'vmForks'`](/config/pool#vmforks) will resolve it. +## Project Working Directory Does Not Change + +In a [multi-project run](/guide/projects), `process.cwd()` in project config files and tests returns the directory where Vitest was started by default. A project's [`root`](/config/root) controls where Vitest looks for its files, but it does not change the process working directory. Vite plugins can read the project root from the resolved Vite config's `root` property. + +If your tests need `process.cwd()` to point to the project directory, use the [`forks` pool](/config/pool#forks) and a project-specific [`setupFiles`](/config/setupfiles) file: + +```ts [packages/lib1/vitest.config.ts] +import { defineProject } from 'vitest/config' + +export default defineProject({ + test: { + pool: 'forks', + setupFiles: ['./setup.chdir.ts'], + }, +}) +``` + +```ts [packages/lib1/setup.chdir.ts] +import { fileURLToPath } from 'node:url' + +process.chdir(fileURLToPath(new URL('.', import.meta.url))) +``` + +This changes the working directory in the test worker, after config loading. The [`threads` pool](/config/pool#threads) cannot use `process.chdir()`. + ## Custom package conditions are not resolved If you are using custom conditions in your `package.json` [exports](https://nodejs.org/api/packages.html#package-entry-points) or [subpath imports](https://nodejs.org/api/packages.html#subpath-imports), you may find that Vitest does not respect these conditions by default. diff --git a/docs/guide/projects.md b/docs/guide/projects.md index 79a6bc4f0..811aeb0fe 100644 --- a/docs/guide/projects.md +++ b/docs/guide/projects.md @@ -171,6 +171,8 @@ export default defineProject({ }) ``` +By default, `process.cwd()` in every project's tests returns the directory where Vitest was started, even if the project has a different root. See [Project Working Directory Does Not Change](/guide/common-errors#project-working-directory-does-not-change) for details and a workaround. + ## Running Tests To run tests, define a script in your root `package.json`: -- 2.51.2