diff --git a/config/detectasyncleaks.md b/config/detectasyncleaks.md new file mode 100644 index 00000000..88c326de --- /dev/null +++ b/config/detectasyncleaks.md @@ -0,0 +1,44 @@ +--- +title: detectAsyncLeaks | Config +outline: deep +--- + +# detectAsyncLeaks + +- **Type:** `boolean` +- **CLI:** `--detectAsyncLeaks`, `--detect-async-leaks` +- **Default:** `false` + +::: warning +Enabling this option will make your tests run much slower. Use only when debugging or developing tests. +::: + +Detect asynchronous resources leaking from the test file. +Uses [`node:async_hooks`](https://nodejs.org/api/async_hooks.html) to track creation of async resources. If a resource is not cleaned up, it will be logged after tests have finished. + +For example if your code has `setTimeout` calls that execute the callback after tests have finished, you will see following error: + +```sh +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Async Leaks 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ + +Timeout leaking in test/checkout-screen.test.tsx + 26| + 27| useEffect(() => { + 28| setTimeout(() => setWindowWidth(window.innerWidth), 150) + | ^ + 29| }) + 30| +``` + +To fix this, you'll need to make sure your code cleans the timeout properly: + +```js +useEffect(() => { + setTimeout(() => setWindowWidth(window.innerWidth), 150) // [!code --] + const timeout = setTimeout(() => setWindowWidth(window.innerWidth), 150) // [!code ++] + + return function cleanup() { // [!code ++] + clearTimeout(timeout) // [!code ++] + } // [!code ++] +}) +``` diff --git a/guide/cli-generated.md b/guide/cli-generated.md index bf9ab25c..7e3bc809 100644 --- a/guide/cli-generated.md +++ b/guide/cli-generated.md @@ -463,6 +463,13 @@ Memory limit for VM pools. If you see memory leaks, try to tinker this value. - **配置:** [logHeapUsage](/config/logheapusage) 在节点中运行时,显示每个测试的堆大小 + +### detectAsyncLeaks + +- **CLI:** `--detectAsyncLeaks` +- **Config:** [detectAsyncLeaks](/config/detectasyncleaks) + +Detect asynchronous resources leaking from the test file (default: `false`) ### allowOnly diff --git a/guide/cli.md b/guide/cli.md index ed0b9053..53607472 100644 --- a/guide/cli.md +++ b/guide/cli.md @@ -122,6 +122,8 @@ vitest list --filesOnly tests/test1.test.ts tests/test2.test.ts ``` + +Since Vitest 4.1, you may pass `--static-parse` to [parse test files](/api/advanced/vitest#parsespecifications) instead of running them to collect tests. Vitest parses test files with limited concurrency, defaulting to `os.availableParallelism()`. You can change it via the `--static-parse-concurrency` option. ## Shell 自动补全 {#shell-autocompletions}