できない.dev

Vitest を 3 から 4 に上げると動かなくなること

Vitest を 3 から 4 に上げると、アロー関数で書いたモックを new すると TypeError になり、vitest.workspace.js や environmentMatchGlobs が黙って無視される。
3 と 4 で同じテストを打ち比べた 10 の変更点と直し方をまとめる。

公開:

vitest@3 を入れたプロジェクトと、同じファイルのまま vitest@4 に上げたプロジェクトを並べ、同じコマンドを打ち比べた。
カバレッジの変更点のために @vitest/coverage-v8 を Vitest と同じ版で入れ、DOM を使う変更点のために jsdom も入れた。
両方のプロジェクトの package.json には "type": "module" を書いてある。
各節の出力は「v3 では」「v4 に上げると」「v4 で直すと」の 3 段で並ぶ。

公式の移行ガイドによると、4.0 は Node.js 20 以上と Vite 6 以上を求める。
npm は vitest@3 には Vite 7.3.8 を、vitest@4 には Vite 8.3.8 を入れた。

動かなくなる原因は 3 つに分かれる。

  • 3.2 で非推奨になっていた設定と書き方が無くなった。
    test の 3 つ目の引数と basic レポーターはエラーで止まる。
    vitest.workspace.js と environmentMatchGlobs は何も知らせずに読まれなくなり、その設定に頼っていたテストが落ちる(このページでは ReferenceError)。
    poolOptions は警告が出るだけで、中身は効かない。
  • モックの作り方が変わった。
    アロー関数の実装を new で呼べなくなり、restoreMocks が vi.fn() の記録を消さなくなり、スナップショットに出るモックの名前が変わった。
  • カバレッジの表と、テストを探す範囲の既定が変わった。
    このページの実行では、どちらも変わったことを知らせる行は出ず、終了コードも 0 のままだった。

上げる前に 3.2 で npx vitest run を打つと、vitest.workspace.js・environmentMatchGlobs・basic レポーター・3 つ目の引数の 4 つは、DEPRECATED か deprecated を含む行で先に分かる。
ほかの 6 つは、このページの 3.2.7 の出力に予告が出なかった。

次の変更は、このページでは打っていない。
どれも公式の移行ガイドか 4.0.0 のリリースノートに載っている。

  • V8 のカバレッジで、カバレッジから外すコメント(ignore ヒント)の扱いが変わった。
    coverage.ignoreEmptyLines と coverage.experimentalAstAwareRemapping は無くなった。
  • ブラウザモードは、プロバイダーを @vitest/browser-playwright などの別のパッケージから渡す形になった。
    @vitest/browser/context の読み込みは vitest/browser に移り、browser.testerScripts は無くなった。
  • vite-node はモジュールランナーに置き換わった。
    カスタム環境は transformMode の代わりに viteEnvironment を書き、deps.optimizer.web は deps.optimizer.client に名前が変わった。
  • poolMatchGlobs と minWorkers は無くなった。
    deps.external・deps.inline・deps.fallbackCJS も無くなり、server.deps の下に書く。
    プールのほかの設定の変更は、poolOptions の節に挙げた。
  • レポーターの古い API(onCollected など)が無くなった。
    verbose レポーターはテストを平らな一覧で出すようになり、木の形で出すには tree レポーターを使う。
  • スナップショットに、カスタム要素の shadow root が出るようになった。
    リリースノートによると、CI では使われなくなったスナップショットが残っているとテストが落ちる。
  • 自動モックの getter が undefined を返すようになったことなど、モックの細かな変更がある。
    --standalone にファイル名を渡すと、そのファイルをすぐに走らせるようになった。
  • リリースノートによると、非推奨の型が無くなった。
    UserConfig は ViteUserConfig に置き換わり、Node.js 側の型は vitest/node から読み込む。
  • 設定の test.workspace は無くなった。
    リリースノートによると、test.projects に並べる設定ファイルは、名前に vitest.config か vite.config を含むものに限られた。

テストで読み込まれなかったファイルがカバレッジに出なくなった

3.2 の coverage.all は既定で true で、テストが一度も読み込まなかったファイルも 0% としてカバレッジの表に載せていた。
4 で coverage.all は無くなった。
公式の移行ガイドによると、coverage.include を書いていないときは、テストの実行中に読み込まれたファイルだけが表に載る。

v3 では

$ ls src
discount.js
sum.js
sum.test.js
$ npx vitest run --coverage
 RUN  v3.2.7 /work/v3/coverage-uncovered
      Coverage enabled with v8
 
 ✓ src/sum.test.js (1 test) 2ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:01
   Duration  289ms (transform 21ms, setup 0ms, collect 12ms, tests 2ms, environment 0ms, prepare 86ms)
 
 % Coverage report from v8
-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |      20 |       50 |      50 |      20 |                   
 discount.js |       0 |        0 |       0 |       0 | 1-4               
 sum.js      |     100 |      100 |     100 |     100 |                   
-------------|---------|----------|---------|---------|-------------------
$ echo $?
0

v4 に上げると

$ node -p 'require("vitest/package.json").peerDependencies["@vitest/coverage-v8"]'
4.1.12
$ npx vitest run --coverage
 RUN  v4.1.12 /work/v4/coverage-uncovered
      Coverage enabled with v8
 
 ✓ src/sum.test.js (1 test) 2ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:02
   Duration  121ms (transform 14ms, setup 0ms, import 23ms, tests 2ms, environment 0ms)
 
 % Coverage report from v8
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 sum.js   |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
$ echo $?
0

v4 で直すと

$ cat vitest.config.js
import { defineConfig } from "vitest/config";
 
export default defineConfig({
  test: {
    coverage: { include: ["src/**"] },
  },
});
$ npx vitest run --coverage
 RUN  v4.1.12 /work/v4/coverage-uncovered
      Coverage enabled with v8
 
 ✓ src/sum.test.js (1 test) 2ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:03
   Duration  131ms (transform 15ms, setup 0ms, import 24ms, tests 2ms, environment 0ms)
 
 % Coverage report from v8
-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |      40 |        0 |      50 |   33.33 |                   
 discount.js |       0 |        0 |       0 |       0 | 2-3               
 sum.js      |     100 |      100 |     100 |     100 |                   
-------------|---------|----------|---------|---------|-------------------
$ echo $?
0

v4 では discount.js が表から消え、All files の行は 20% から 100% に上がった。
終了コードは v3 と同じ 0 で、v4 はファイルが減ったことを知らせない。

「v4 に上げると」の最初のコマンドのとおり、vitest@4.1.12 は peerDependencies で @vitest/coverage-v8 に同じ 4.1.12 を指定している。
カバレッジのパッケージも Vitest と一緒に上げる。

カバレッジを測るファイルを coverage.include に書くと、読み込まれなかったファイルも表に戻る。
公式の移行ガイドは、上げるときに coverage.include を書き、要るなら coverage.exclude で外すよう勧めている。
coverage.all と coverage.extensions は設定から消す。

直したあとの表では、discount.js の未実行の行が v3 の「1-4」から「2-3」に変わり、All files の割合も v3 と揃わなかった。
公式の移行ガイドによると、4 は V8 のカバレッジを元のファイルに対応付ける仕組みを作り直したので、3 から上げるとカバレッジの数字が変わる。

dist の下のテストも走るようになった

3.2 の exclude の既定は、node_modules のほかに dist・cypress・.idea などのディレクトリや、vite.config.* などの設定ファイルを含んでいた。
4 の既定は node_modules と .git の 2 つだけになった。
ビルドの出力にテストのファイルが入るプロジェクトでは、dist の下のテストも走る。
ここでは src をそのまま dist に写して、ビルドの出力の代わりにした。

v3 では

$ ls src dist
dist:
sum.js
sum.test.js
 
src:
sum.js
sum.test.js
$ npx vitest run
 RUN  v3.2.7 /work/v3/default-exclude
 
 ✓ src/sum.test.js (1 test) 1ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:03
   Duration  312ms (transform 19ms, setup 0ms, collect 14ms, tests 1ms, environment 0ms, prepare 65ms)
$ echo $?
0

v4 に上げると

$ npx vitest run
 RUN  v4.1.12 /work/v4/default-exclude
 
 ✓ dist/sum.test.js (1 test) 1ms
 ✓ src/sum.test.js (1 test) 2ms
 
 Test Files  2 passed (2)
      Tests  2 passed (2)
   Start at  01:43:04
   Duration  121ms (transform 27ms, setup 0ms, import 43ms, tests 4ms, environment 0ms)
$ echo $?
0

v4 で直すと

$ cat vitest.config.js
import { configDefaults, defineConfig } from "vitest/config";
 
export default defineConfig({
  test: {
    exclude: [...configDefaults.exclude, "**/dist/**"],
  },
});
$ npx vitest run
 RUN  v4.1.12 /work/v4/default-exclude
 
 ✓ src/sum.test.js (1 test) 1ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:04
   Duration  115ms (transform 17ms, setup 0ms, import 27ms, tests 1ms, environment 0ms)
$ echo $?
0

v4 では dist/sum.test.js も走り、テストのファイルが 2 つに増えた。
どちらも通ったので終了コードは 0 だが、dist に古いビルドが残っていれば、古いコードのテストが結果に混ざる。

設定に exclude を書くと既定の値は置き換わるので、configDefaults.exclude を展開してから "**/dist/**" を足す。
公式の移行ガイドは、テストのあるディレクトリが決まっているなら、除く範囲を並べるよりも test.dir で探す場所を絞るよう勧めている。
3.2 と同じ範囲に戻すための一覧も、ガイドに載っている。

アロー関数で書いたモックを new できなくなった

vi.mock でクラスを差し替えるとき、3 では vi.fn(() => ({ ... })) のようにアロー関数で書いても、new したコードは返したオブジェクトを受け取れた。
公式の移行ガイドによると、4 は new で呼ばれたモックを、実装を関数として呼ぶのではなくコンストラクタとして呼ぶ。
そのため実装は function か class で書く必要があり、アロー関数は new できない。

v3 では

$ cat user.js
import { ApiClient } from "./client.js";
 
export function loadUserName() {
  const client = new ApiClient();
  return client.get("/user");
}
$ cat user.test.js
import { expect, test, vi } from "vitest";
import { loadUserName } from "./user.js";
 
vi.mock("./client.js", () => ({
  ApiClient: vi.fn(() => ({ get: vi.fn(() => "sato") })),
}));
 
test("loadUserName", () => {
  expect(loadUserName()).toBe("sato");
});
$ npx vitest run
 RUN  v3.2.7 /work/v3/mock-constructor
 
 ✓ user.test.js (1 test) 1ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:05
   Duration  237ms (transform 26ms, setup 0ms, collect 22ms, tests 1ms, environment 0ms, prepare 74ms)
$ echo $?
0

v4 に上げると

$ npx vitest run
 RUN  v4.1.12 /work/v4/mock-constructor
 
stderr | user.test.js > loadUserName
[vitest] The vi.fn() mock did not use 'function' or 'class' in its implementation, see https://vitest.dev/api/vi#vi-spyon for examples.
 
 ❯ user.test.js (1 test | 1 failed) 4ms
   × loadUserName 3ms
 
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
 
 FAIL  user.test.js > loadUserName
TypeError: () => ({ get: vi.fn(() => "sato") }) is not a constructor
 ❯ Module.loadUserName user.js:4:18
      2|
      3| export function loadUserName() {
      4|   const client = new ApiClient();
       |                  ^
      5|   return client.get("/user");
      6| }
 ❯ user.test.js:9:10
 
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
 
 Test Files  1 failed (1)
      Tests  1 failed (1)
   Start at  01:43:06
   Duration  113ms (transform 19ms, setup 0ms, import 29ms, tests 4ms, environment 0ms)
$ echo $?
1

v4 で直すと

$ cat user.test.js
import { expect, test, vi } from "vitest";
import { loadUserName } from "./user.js";
 
vi.mock("./client.js", () => ({
  ApiClient: vi.fn(function () {
    this.get = vi.fn(() => "sato");
  }),
}));
 
test("loadUserName", () => {
  expect(loadUserName()).toBe("sato");
});
$ npx vitest run
 RUN  v4.1.12 /work/v4/mock-constructor
 
 ✓ user.test.js (1 test) 2ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:06
   Duration  98ms (transform 19ms, setup 0ms, import 29ms, tests 2ms, environment 0ms)
$ echo $?
0

v4 では、new ApiClient() の行で TypeError になった。
エラー文には、渡したアロー関数のソースがそのまま入る。
直前の stderr には、実装に function も class も使っていないという [vitest] の警告が出ていた。

実装を function で書き、返していたメソッドを this に付けると通る。
公式の移行ガイドは、class で書く方法も挙げている。
vi.spyOn でクラスを差し替えて mockImplementation にアロー関数を渡している場合も、ガイドによると同じく function か class に書き換える。

restoreMocks が vi.fn() の呼び出しの記録を消さなくなった

restoreMocks: true は、各テストの前にモックを元に戻す設定である。
3.2 の設定のページによると、3 ではすべてのモックに .mockRestore() を呼び、呼び出しの記録も消していた。
公式の移行ガイドによると、4 の vi.restoreAllMocks と restoreMocks は vi.spyOn で作ったものだけを戻し、記録を消さない。

v3 では

$ cat vitest.config.js
import { defineConfig } from "vitest/config";
 
export default defineConfig({
  test: { restoreMocks: true },
});
$ cat notify.test.js
import { expect, test, vi } from "vitest";
import { notify } from "./notify.js";
 
const send = vi.fn();
 
test("sends a welcome mail", () => {
  notify(send, "welcome");
  expect(send).toHaveBeenCalledTimes(1);
});
 
test("sends a reminder mail", () => {
  notify(send, "reminder");
  expect(send).toHaveBeenCalledTimes(1);
});
$ npx vitest run
 RUN  v3.2.7 /work/v3/restore-mocks
 
 ✓ notify.test.js (2 tests) 2ms
 
 Test Files  1 passed (1)
      Tests  2 passed (2)
   Start at  01:43:06
   Duration  242ms (transform 24ms, setup 0ms, collect 15ms, tests 2ms, environment 0ms, prepare 80ms)
$ echo $?
0

v4 に上げると

$ npx vitest run
 RUN  v4.1.12 /work/v4/restore-mocks
 
 ❯ notify.test.js (2 tests | 1 failed) 6ms
   ✓ sends a welcome mail 2ms
   × sends a reminder mail 3ms
 
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
 
 FAIL  notify.test.js > sends a reminder mail
AssertionError: expected "vi.fn()" to be called 1 times, but got 2 times
 ❯ notify.test.js:13:16
     11| test("sends a reminder mail", () => {
     12|   notify(send, "reminder");
     13|   expect(send).toHaveBeenCalledTimes(1);
       |                ^
     14| });
     15|
 
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
 
 Test Files  1 failed (1)
      Tests  1 failed | 1 passed (2)
   Start at  01:43:07
   Duration  111ms (transform 14ms, setup 0ms, import 24ms, tests 6ms, environment 0ms)
$ echo $?
1

v4 で直すと

$ cat vitest.config.js
import { defineConfig } from "vitest/config";
 
export default defineConfig({
  test: { restoreMocks: true, clearMocks: true },
});
$ npx vitest run
 RUN  v4.1.12 /work/v4/restore-mocks
 
 ✓ notify.test.js (2 tests) 2ms
 
 Test Files  1 passed (1)
      Tests  2 passed (2)
   Start at  01:43:08
   Duration  88ms (transform 11ms, setup 0ms, import 19ms, tests 2ms, environment 0ms)
$ echo $?
0

v4 では、2 本目のテストが send の呼び出しを 2 回と数えて落ちた。
ファイルの最上位で作った vi.fn() は記録が消えず、1 本目の呼び出しが残っている。

呼び出しの記録をテストごとに消すには、clearMocks: true を足す。
4 の設定のページによると、clearMocks は実装を変えずに記録だけを消す。
mockReturnValue などで変えた振る舞いもテストごとに戻したいなら mockReset: true を使い、こちらは記録を消して実装も戻す。
このページでは mockReset は打っていない。

スナップショットの [MockFunction spy] が [MockFunction] になった

公式の移行ガイドによると、4 の vi.fn() の名前は既定で spy から vi.fn() に変わった。
スナップショットの中のモックは、[MockFunction spy] から [MockFunction] に変わる。
3 で撮ってコミットしたスナップショットは、中身が同じでも一致しなくなる。

v3 では

$ cat button.test.js
import { expect, test, vi } from "vitest";
import { createButton } from "./button.js";
 
test("createButton", () => {
  const onClick = vi.fn();
  expect(createButton({ label: "OK", onClick })).toMatchSnapshot();
});
$ npx vitest run
 RUN  v3.2.7 /work/v3/mock-name
 
 ✓ button.test.js (1 test) 2ms
 
  Snapshots  1 written
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:08
   Duration  331ms (transform 27ms, setup 0ms, collect 13ms, tests 2ms, environment 0ms, prepare 89ms)
$ echo $?
0
$ cat __snapshots__/button.test.js.snap
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
 
exports[`createButton 1`] = `
{
  "label": "OK",
  "onClick": [MockFunction spy],
  "type": "button",
}
`;

v4 に上げると

$ npx vitest run
 RUN  v4.1.12 /work/v4/mock-name
 
 ❯ button.test.js (1 test | 1 failed) 5ms
   × createButton 5ms
 
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
 
 FAIL  button.test.js > createButton
Error: Snapshot `createButton 1` mismatched
 
- Expected
+ Received
 
  {
    "label": "OK",
-   "onClick": [MockFunction spy],
+   "onClick": [MockFunction],
    "type": "button",
  }
 
 ❯ button.test.js:6:50
      4| test("createButton", () => {
      5|   const onClick = vi.fn();
      6|   expect(createButton({ label: "OK", onClick })).toMatchSnapshot();
       |                                                  ^
      7| });
      8|
 
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
 
  Snapshots  1 failed
 Test Files  1 failed (1)
      Tests  1 failed (1)
   Start at  01:43:09
   Duration  111ms (transform 15ms, setup 0ms, import 22ms, tests 5ms, environment 0ms)
$ echo $?
1

v4 で直すと

$ npx vitest run -u
 RUN  v4.1.12 /work/v4/mock-name
 
 ✓ button.test.js (1 test) 3ms
 
  Snapshots  1 updated 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:09
   Duration  109ms (transform 14ms, setup 0ms, import 26ms, tests 3ms, environment 0ms)
$ echo $?
0
$ cat __snapshots__/button.test.js.snap
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
 
exports[`createButton 1`] = `
{
  "label": "OK",
  "onClick": [MockFunction],
  "type": "button",
}
`;

v4 では、差分が onClick の行だけに出てテストが落ちた。
モックの名前のほかは、3 で撮ったスナップショットと変わっていない。

npx vitest run -u でスナップショットを撮り直すと通る。
撮り直す前に、差分がモックの名前の行だけであることを確かめておくと、ほかの変化を見落とさずに済む。
ガイドによると、vi.spyOn で作ったモックは元の関数の名前を使い続ける。

vitest.workspace.js が読まれなくなった

公式の移行ガイドによると、ワークスペースの設定は 3.2 で projects に名前が変わった。
3.2 は vitest.workspace.js を読みながら警告を出していたが、4 はファイルを読まない。
4 に上げると、ルートの設定だけでテストが走り、ワークスペースに書いた globals: true などは効かなくなる。

v3 では

$ cat vitest.workspace.js
import { defineWorkspace } from "vitest/config";
 
export default defineWorkspace([
  {
    test: { name: "web", root: "./packages/web", globals: true },
  },
]);
$ cat packages/web/sum.test.js
describe("sum", () => {
  it("adds", () => {
    expect(1 + 2).toBe(3);
  });
});
$ npx vitest run
 DEPRECATED  The workspace file is deprecated and will be removed in the next major. Please, use the `test.projects` field in the root config file instead.
 
 RUN  v3.2.7 /work/v3/workspace-file
 
 ✓ |web| sum.test.js (1 test) 1ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:10
   Duration  237ms (transform 7ms, setup 0ms, collect 5ms, tests 1ms, environment 0ms, prepare 57ms)
$ echo $?
0

v4 に上げると

$ npx vitest run
 RUN  v4.1.12 /work/v4/workspace-file
 
 ❯ packages/web/sum.test.js (0 test)
 
⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯
 
 FAIL  packages/web/sum.test.js [ packages/web/sum.test.js ]
ReferenceError: describe is not defined
 ❯ packages/web/sum.test.js:1:1
      1| describe("sum", () => {
       | ^
      2|   it("adds", () => {
      3|     expect(1 + 2).toBe(3);
 
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
 
 Test Files  1 failed (1)
      Tests  no tests
   Start at  01:43:10
   Duration  88ms (transform 8ms, setup 0ms, import 0ms, tests 0ms, environment 0ms)
$ echo $?
1

v4 で直すと

$ rm vitest.workspace.js
$ cat vitest.config.js
import { defineConfig } from "vitest/config";
 
export default defineConfig({
  test: {
    projects: [
      {
        test: { name: "web", root: "./packages/web", globals: true },
      },
    ],
  },
});
$ npx vitest run
 RUN  v4.1.12 /work/v4/workspace-file
 
 ✓ |web| sum.test.js (1 test) 2ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:11
   Duration  95ms (transform 9ms, setup 0ms, import 14ms, tests 2ms, environment 0ms)
$ echo $?
0

v4 では、vitest.workspace.js について何も出力せずにテストを走らせた。
globals: true が効かないので、describe が定義されていないエラーになった。
v3 の出力にあった |web| のプロジェクト名も消えている。

ワークスペースのファイルに書いていた配列を、ルートの設定の test.projects に移し、ファイルは消す。
公式の移行ガイドによると、projects はワークスペースと同じ働きをするが、プロジェクトの一覧を別のファイルに置くことはできない。
直したあとは |web| の名前が戻り、テストも通った。

poolOptions の中身が test の直下に移った

公式の移行ガイドによると、4 はテストを走らせるプールを作り直し、poolOptions を無くした。
poolOptions の中に書いていた項目は test の直下に置く。
4 は poolOptions を見つけると警告を出すが、中身は使わない。

v3 では

$ cat vitest.config.js
import { defineConfig } from "vitest/config";
 
export default defineConfig({
  test: {
    poolOptions: {
      forks: { execArgv: ["--expose-gc"] },
    },
  },
});
$ cat memory.test.js
import { expect, test } from "vitest";
 
test("gc is exposed", () => {
  expect(typeof globalThis.gc).toBe("function");
});
$ npx vitest run
 RUN  v3.2.7 /work/v3/pool-options
 
 ✓ memory.test.js (1 test) 3ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:11
   Duration  279ms (transform 21ms, setup 0ms, collect 14ms, tests 3ms, environment 0ms, prepare 91ms)
$ echo $?
0

v4 に上げると

$ npx vitest run
 DEPRECATED  `test.poolOptions` was removed in Vitest 4. All previous `poolOptions` are now top-level options. Please, refer to the migration guide: https://vitest.dev/guide/migration#pool-rework
 
 RUN  v4.1.12 /work/v4/pool-options
 
 ❯ memory.test.js (1 test | 1 failed) 5ms
   × gc is exposed 4ms
 
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
 
 FAIL  memory.test.js > gc is exposed
AssertionError: expected 'undefined' to be 'function' // Object.is equality
 
Expected: "function"
Received: "undefined"
 
 ❯ memory.test.js:4:32
      2|
      3| test("gc is exposed", () => {
      4|   expect(typeof globalThis.gc).toBe("function");
       |                                ^
      5| });
      6|
 
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
 
 Test Files  1 failed (1)
      Tests  1 failed (1)
   Start at  01:43:12
   Duration  94ms (transform 9ms, setup 0ms, import 15ms, tests 5ms, environment 0ms)
$ echo $?
1

v4 で直すと

$ cat vitest.config.js
import { defineConfig } from "vitest/config";
 
export default defineConfig({
  test: {
    execArgv: ["--expose-gc"],
  },
});
$ npx vitest run
 RUN  v4.1.12 /work/v4/pool-options
 
 ✓ memory.test.js (1 test) 1ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:12
   Duration  108ms (transform 10ms, setup 0ms, import 17ms, tests 1ms, environment 0ms)
$ echo $?
0

v4 では DEPRECATED の行が出たあと、--expose-gc が効かないまま走り、globalThis.gc が undefined になった。
v3 の出力には、poolOptions についての予告は出ていなかった。

execArgv を test の直下に移すと通る。

プールのほかの設定は、このページでは打っていない。
公式の移行ガイドによると、maxThreads と maxForks は maxWorkers にまとまり、環境変数も VITEST_MAX_WORKERS になった。
VM のプールの memoryLimit は vmMemoryLimit に名前が変わり、threads.useAtomics は無くなった。

singleThread と singleFork は、maxWorkers: 1 と isolate: false に置き換わった。
ガイドによると、テストの間でモジュールがリセットされることに頼っていたなら、beforeAll で vi.resetModules() を呼ぶセットアップファイルを足す。

basic レポーターが無くなった

basic は 3.2 まで組み込みのレポーターの 1 つだった。
4 で無くなり、--reporter=basic を渡すと起動の段階で止まる。

v3 では

$ npx vitest run --reporter=basic
 RUN  v3.2.7 /work/v3/basic-reporter
 
 DEPRECATED  'basic' reporter is deprecated and will be removed in Vitest v3.
Remove 'basic' from 'reporters' option. To match 'basic' reporter 100%, use configuration:
{
  "test": {
    "reporters": [
      [
        "default",
        {
          "summary": false
        }
      ]
    ]
  }
}
 ✓ sum.test.js (1 test) 1ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:13
   Duration  235ms (transform 16ms, setup 0ms, collect 11ms, tests 1ms, environment 0ms, prepare 74ms)
$ echo $?
0

v4 に上げると

$ npx vitest run --reporter=basic
⎯⎯⎯⎯⎯⎯⎯ Startup Error ⎯⎯⎯⎯⎯⎯⎯⎯
Error: Failed to load custom Reporter from basic
    at loadCustomReporterModule (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:11429:9)
    at async file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:11445:23
    ... 3 lines matching cause stack trace ...
    at async _createServer (file:///work/v4/node_modules/vite/dist/node/chunks/node.js:25018:84)
    at async createViteServer (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:8902:17)
    at async createVitest (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:14288:18)
    at async prepareVitest (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:14655:14)
    at async startVitest (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:14598:14) {
  [cause]: Error: Failed to load url basic (resolved id: basic). Does the file exist?
      at reviveInvokeError (file:///work/v4/node_modules/vite/dist/node/module-runner.js:546:14)
      at Object.invoke (file:///work/v4/node_modules/vite/dist/node/module-runner.js:562:33)
      at async ServerModuleRunner.getModuleInformation (file:///work/v4/node_modules/vite/dist/node/module-runner.js:1202:7)
      at async ServerModuleRunner.import (file:///work/v4/node_modules/vite/dist/node/module-runner.js:1123:23)
      at async loadCustomReporterModule (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:11427:26)
      at async file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:11445:23
      at async Promise.all (index 0)
      at async Vitest._setServer (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:13244:138)
      at async BasicMinimalPluginContext.handler (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:14258:5)
      at async _createServer (file:///work/v4/node_modules/vite/dist/node/chunks/node.js:25018:84) {
    code: 'ERR_LOAD_URL',
    runnerError: Error: RunnerError
        at reviveInvokeError (file:///work/v4/node_modules/vite/dist/node/module-runner.js:547:64)
        at Object.invoke (file:///work/v4/node_modules/vite/dist/node/module-runner.js:562:33)
        at async ServerModuleRunner.getModuleInformation (file:///work/v4/node_modules/vite/dist/node/module-runner.js:1202:7)
        at async ServerModuleRunner.import (file:///work/v4/node_modules/vite/dist/node/module-runner.js:1123:23)
        at async loadCustomReporterModule (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:11427:26)
        at async file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:11445:23
        at async Promise.all (index 0)
        at async Vitest._setServer (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:13244:138)
        at async BasicMinimalPluginContext.handler (file:///work/v4/node_modules/vitest/dist/chunks/cli-api.B0Pz1_R7.js:14258:5)
        at async _createServer (file:///work/v4/node_modules/vite/dist/node/chunks/node.js:25018:84)
  }
}
$ echo $?
1

v4 で直すと

$ cat vitest.config.js
import { defineConfig } from "vitest/config";
 
export default defineConfig({
  test: {
    reporters: [["default", { summary: false }]],
  },
});
$ npx vitest run
 RUN  v4.1.12 /work/v4/basic-reporter
 
 ✓ sum.test.js (1 test) 2ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:14
   Duration  93ms (transform 11ms, setup 0ms, import 18ms, tests 2ms, environment 0ms)
$ echo $?
0

v4 は basic を組み込みのレポーターとして扱わず、同じ名前のファイルを読み込もうとして失敗した。
v3 の警告は「Vitest v3 で無くなる」と書いていたが、3.2.7 では動いており、実際に無くなったのは 4 である。

公式の移行ガイドによると、basic は default レポーターに summary: false を渡したものと同じである。
4 のレポーターのガイドによると、summary は実行中のテストとその状況を画面の下に出す表示を指す。
コマンドラインの --reporter=basic を消し、設定ファイルの reporters に書く。

environmentMatchGlobs が無くなった

environmentMatchGlobs は、ファイル名の glob ごとにテストの環境を決める設定だった。
4 で無くなり、4 は設定に残っていても何も知らせない。
jsdom で走らせていたファイルも、既定の node 環境で走る。

v3 では

$ cat vitest.config.js
import { defineConfig } from "vitest/config";
 
export default defineConfig({
  test: {
    environmentMatchGlobs: [["**/*.dom.test.js", "jsdom"]],
  },
});
$ cat title.dom.test.js
import { expect, test } from "vitest";
 
test("sets the title", () => {
  document.title = "hello";
  expect(document.title).toBe("hello");
});
$ npx vitest run
 DEPRECATED  "environmentMatchGlobs" is deprecated. Use `test.projects` to define different configurations instead.
 
 RUN  v3.2.7 /work/v3/environment-match-globs
 
 ✓ sum.test.js (1 test) 2ms
 ✓ title.dom.test.js (1 test) 2ms
 
 Test Files  2 passed (2)
      Tests  2 passed (2)
   Start at  01:43:14
   Duration  522ms (transform 45ms, setup 0ms, collect 13ms, tests 4ms, environment 280ms, prepare 170ms)
$ echo $?
0

v4 に上げると

$ npx vitest run
 RUN  v4.1.12 /work/v4/environment-match-globs
 
 ❯ title.dom.test.js (1 test | 1 failed) 3ms
   × sets the title 2ms
 ✓ sum.test.js (1 test) 1ms
 
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
 
 FAIL  title.dom.test.js > sets the title
ReferenceError: document is not defined
 ❯ title.dom.test.js:4:3
      2|
      3| test("sets the title", () => {
      4|   document.title = "hello";
       |   ^
      5|   expect(document.title).toBe("hello");
      6| });
 
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
 
 Test Files  1 failed | 1 passed (2)
      Tests  1 failed | 1 passed (2)
   Start at  01:43:15
   Duration  96ms (transform 16ms, setup 0ms, import 29ms, tests 4ms, environment 0ms)
$ echo $?
1

v4 で直すと

$ cat vitest.config.js
import { configDefaults, defineConfig } from "vitest/config";
 
export default defineConfig({
  test: {
    projects: [
      {
        test: {
          name: "dom",
          include: ["**/*.dom.test.js"],
          environment: "jsdom",
        },
      },
      {
        test: {
          name: "node",
          exclude: [...configDefaults.exclude, "**/*.dom.test.js"],
        },
      },
    ],
  },
});
$ npx vitest run
 RUN  v4.1.12 /work/v4/environment-match-globs
 
 ✓ |node| sum.test.js (1 test) 1ms
 ✓ |dom| title.dom.test.js (1 test) 3ms
 
 Test Files  2 passed (2)
      Tests  2 passed (2)
   Start at  01:43:16
   Duration  343ms (transform 13ms, setup 0ms, import 25ms, tests 4ms, environment 256ms)
$ echo $?
0

v4 では、title.dom.test.js だけが document の無い環境で走って落ちた。
DOM を使わない sum.test.js は通っている。

公式の移行ガイドは、代わりに test.projects で環境ごとにプロジェクトを分けるよう勧めている。
直したあとは |dom| と |node| の 2 つのプロジェクトに分かれ、2 本とも通った。

jsdom のプロジェクトは include で対象のファイルを決め、node のプロジェクトは exclude でそのファイルを外す。
exclude を書くと既定の値が置き換わるので、configDefaults.exclude を展開しておく。

4 の projects のガイドによると、test.projects に書いたプロジェクトはルートの設定を引き継がない。
ルートに globals や setupFiles を書いているなら、各プロジェクトに extends: true を足す。
このページのルートの設定には projects しか無いので、extends は書いていない。

test の 3 つ目の引数にオプションを渡せなくなった

test と describe の 3 つ目の引数に { retry: 2 } のようなオプションを渡す書き方は、3 で非推奨になり、4 で無くなった。
4 はファイルを読み込む段階で TypeError を出し、そのファイルのテストは 1 本も走らない。

v3 では

$ cat retry.test.js
import { expect, test } from "vitest";
 
let attempts = 0;
 
test("succeeds on the second attempt", () => {
  attempts += 1;
  expect(attempts).toBe(2);
}, { retry: 2 });
$ npx vitest run
 RUN  v3.2.7 /work/v3/test-options-arg
 
stderr | retry.test.js
Using an object as a third argument is deprecated. Vitest 4 will throw an error if the third argument is not a timeout number. Please use the second argument for options. See more at https://vitest.dev/guide/migration
 
 ✓ retry.test.js (1 test) 7ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:16
   Duration  225ms (transform 15ms, setup 0ms, collect 8ms, tests 7ms, environment 0ms, prepare 67ms)
$ echo $?
0

v4 に上げると

$ npx vitest run
 RUN  v4.1.12 /work/v4/test-options-arg
 
 ❯ retry.test.js (0 test)
 
⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯
 
 FAIL  retry.test.js [ retry.test.js ]
TypeError: Signature "test(name, fn, { ... })" was deprecated in Vitest 3 and removed in Vitest 4. Please, provide options as a second argument instead.
 ❯ retry.test.js:5:1
      3| let attempts = 0;
      4|
      5| test("succeeds on the second attempt", () => {
       | ^
      6|   attempts += 1;
      7|   expect(attempts).toBe(2);
 
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
 
 Test Files  1 failed (1)
      Tests  no tests
   Start at  01:43:17
   Duration  105ms (transform 10ms, setup 0ms, import 0ms, tests 0ms, environment 0ms)
$ echo $?
1

v4 で直すと

$ cat retry.test.js
import { expect, test } from "vitest";
 
let attempts = 0;
 
test("succeeds on the second attempt", { retry: 2 }, () => {
  attempts += 1;
  expect(attempts).toBe(2);
});
$ npx vitest run
 RUN  v4.1.12 /work/v4/test-options-arg
 
 ✓ retry.test.js (1 test) 5ms
 
 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  01:43:18
   Duration  99ms (transform 10ms, setup 0ms, import 17ms, tests 5ms, environment 0ms)
$ echo $?
0

v3 の警告は「Vitest 4 will throw an error」と予告しており、4 ではそのとおりエラーで止まった。
テストの関数を 3 つ目に回し、オプションを 2 つ目に置くと通る。
公式の移行ガイドによると、3 つ目の引数にタイムアウトの数値を渡す書き方は 4 でも使える。

検証環境Node.js 24.22.3 / npm 11.19.1 / Python 3.11.2 / 2026-11-13 検証(ほか 8 件)
検証日
実行環境
node:24 Debian GNU/Linux 12 (bookworm)
バージョン
  • Node.js 24.22.3
  • npm 11.19.1
  • Python 3.11.2
  • Git 2.39.5
  • Vitest(旧) 3.2.7
  • Vitest(新) 4.1.12
  • @vitest/coverage-v8(旧) 3.2.7
  • @vitest/coverage-v8(新) 4.1.12
  • Vite(旧) 7.3.8
  • Vite(新) 8.3.8
  • jsdom 31.0.0

この記事の「実行例」は、上記の環境で実際にコマンドを実行して得られた出力をそのまま掲載しています。 再現手順はリポジトリの検証スクリプトとして管理し、定期的に再実行して出力を更新しています。