Consider running the web Vitest project without isolation, using a per-file reset setup file

Đang mở
#1,929 2 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
35/100
Loại issue
Tính năng
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Lĩnh vực
devtools, performance, testing

Hướng nghiên cứu

Start by reading .agents/docs/architecture/testing-strategy.md, apps/web/AGENTS.md, and apps/web/vitest.config.ts; the issue includes a throwaway setup file prototype and detailed measurements. Evaluate the speed gains against reset-list risks, especially the unaddressed event listeners and persistent notification store. Done means a documented decision, with any adopted configuration and test strategy validated against the reported shuffled runs and coverage gate.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

Area: Infrastructure Area: Web Chore Difficulty: Medium Needs Decision Performance Priority: Low

Summary

Running the web Vitest project with isolate: false plus one per-file reset setup file roughly triples its speed (about 42s to about 14s) and halves the full test:coverage run (about 62–69s to about 34s). It does this with zero test failures across 10 shuffled file orders and an unchanged 100% coverage gate.

Adopting it breaks the documented "no setup files anywhere" convention, and it turns isolation into a maintained reset list rather than a structural guarantee. Unit tests are only about 15–20% of the CI job, which is dominated by e2e. This issue records the methods and results so the decision can be made on data.

Where the time goes today

  • Web dominates. apps/web is 268 of 469 test files. Alone it takes about 42–59s; the other 22 projects together take about 14s.

  • Most of that is module loading. Vitest's breakdown for web: import 55%, tests 27%, environment 15%, transform 3%. Its import diagnostic: "745 modules were evaluated 4991 times".

  • Import cost is mostly externalized node_modules, re-imported in each fresh worker. For example, @douglasneuroinformatics/libui/components costs about 0.5–1.3s per fresh process.

  • CI, two recent green runs of lint-and-test:

    Step Time
    Lint 35–56s
    Unit tests 2m58s–4m12s
    End-to-end tests 14m52s–18m26s

    Unit tests are about 15–20% of the job.

Why plain isolate: false fails

--project web --no-isolate is fast but fails 22 of 268 files. In Vitest 5.0.2 the per-file resetModules and mocker.reset() run only when config.isolate is true (vitest/dist/chunks/base.*.js). With isolation off, evaluated modules persist across files in a worker. Controlled single-worker pair runs, with an isolated control for each, found three failure classes:

  1. Stale mock bindings. Tests use per-file vi.hoisted objects with vi.mock(..., factory). A shared source module evaluated by an earlier file stays bound to that file's mock, or to the real module.
    • src/utils/error.ts keeps the first file's axios mock. Whichever of useSyncInstrumentRepoMutation.test.ts and useUpdateSeriesInstrumentArchiveMutation.test.ts runs second fails.
    • src/components/LoginPageEditor/hooks.ts, loaded by SectionHeader.test.tsx, makes EnableBrandingCard.test.tsx fail with "No QueryClient set".
  2. vi.resetModules() plus a top-level i18n.init(). Four web test files call vi.resetModules(). That re-evaluates src/services/i18n.ts against libui's surviving singleton and throws "Cannot reinitialize Translator".
  3. Language leak. 13 test files switch to fr or es, and files that never reset to en inherit it.

The leak is symmetric and order-dependent: whichever file loads a shared module second fails. So moving the 22 failing files into a separate isolated project would show up as flakiness, not a fix.

Prototype

isolate: false for web only, plus one setup file. Vitest re-imports a setup file before every test file even without isolation. The setup file does the following:

  • vi.resetModules(): source modules re-evaluate per file, so each file's vi.mock binds fresh, while externalized node_modules stay in Node's cache.
  • i18n.init guard: a second init is a no-op, and the language is reset to en.
  • axios.interceptors.request.clear() and .response.clear(): found during testing (see below).
  • Storage: localStorage and sessionStorage are cleared.
  • Cleanup: afterEach(cleanup).
Prototype patch (throwaway; not for merge as-is)
diff --git a/apps/web/src/testing/shared-worker-setup.ts b/apps/web/src/testing/shared-worker-setup.ts
new file mode 100644
--- /dev/null
+++ b/apps/web/src/testing/shared-worker-setup.ts
@@ -0,0 +1,40 @@
+// PROTOTYPE (not for merge): per-file reset for running the web project with `isolate: false`.
+// Vitest re-imports this setup file before every test file, even without isolation.
+import { i18n } from '@douglasneuroinformatics/libui/i18n';
+import { cleanup } from '@testing-library/react';
+import axios from 'axios';
+import { afterEach, vi } from 'vitest';
+
+// Drop every source module evaluated by the previous file, so `vi.mock` in this file binds fresh;
+// node_modules (externalized) stay in Node's own cache, which is where the import cost is.
+vi.resetModules();
+
+// `@/services/i18n` calls `i18n.init` at module scope; after the reset it runs again against libui's
+// singleton, which survives the reset and throws on a second init.
+const INIT_GUARD = Symbol.for('odc.test.i18n-init-guard');
+const guardedI18n = i18n as typeof i18n & { [INIT_GUARD]?: true };
+if (!guardedI18n[INIT_GUARD]) {
+  const init = i18n.init.bind(i18n);
+  i18n.init = (config) => {
+    if (!i18n.isInitialized) {
+      init(config);
+    }
+  };
+  guardedI18n[INIT_GUARD] = true;
+}
+if (i18n.isInitialized) {
+  i18n.changeLanguage('en');
+}
+
+// `@/services/axios` registers interceptors on the real axios instance at module scope. axios is
+// externalized, so interceptors from an earlier file's evaluation (bound to that file's mocks) would
+// otherwise stay attached.
+axios.interceptors.request.clear();
+axios.interceptors.response.clear();
+
+localStorage.clear();
+sessionStorage.clear();
+
+afterEach(() => {
+  cleanup();
+});
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -15,7 +15,9 @@ export default mergeConfig(
     root: import.meta.dirname,
     test: {
       environment: 'happy-dom',
+      isolate: false,
       name: 'web',
+      setupFiles: ['./src/testing/shared-worker-setup.ts'],
       root: import.meta.dirname
     }
   })

Results

Setup: Vitest 5.0.2, Node 24, Apple M3 Pro (11 cores, 18 GB), default forks pool.

Measurement: wall time is from run start to the last file's end, from the JSON reporter, so it excludes coverage-report generation. The machine was shared and its load average swung between about 3 and 18 during the session, so the ranges are wide; the ratios are the signal.

Run Wall Result
--project web, isolated (today) 42.5s 3,242 tests pass
--project web, prototype, default order 14.2s; 13.1s in a second run at load ~17 3,242 tests pass
--project web, prototype, --sequence.shuffle.files, seeds 1–10 13.2–44.6s (median ~30s) 0 failures in all 10
Full suite with coverage, isolated (today) 61.6s, 68.7s 100%
Full suite with coverage, prototype 33.8s 100%, identical totals (11,508 statements, 6,193 branches, 3,474 functions, 10,948 lines)
  • Duration breakdown. Vitest's breakdown for web moved from import 55%, environment 15% to import 13%, environment 38%, tests 39%.
  • Slow shuffled seeds. The slowest ones coincided with a load average of about 17–18. In them every file was slower (median file end around 19–25s instead of about 5s), not just a long tail.
  • Shuffle and scheduling. --sequence.shuffle.files also disables Vitest's longest-first scheduling.
  • Memory. Heap per worker grew from about 340 MB to a peak of about 580 MB over the run, then levelled off. That is modest, not a runaway leak.

Found while testing

  • Shuffled seed 1 exposed a fourth leak class. src/services/axios.ts registers interceptors on the real, externalized axios instance at module scope, so every re-evaluation stacked another set bound to that file's mocks. services/__tests__/axios.test.ts then failed 7 of 35 tests (duplicate notifications, retries reported to a stale store). Clearing the interceptors in the setup file fixed it, and all 10 seeds then passed.
  • Not addressed, latent:
    • src/services/axios.ts also adds window online/offline listeners at module scope, and these accumulate per file.
    • libui's real useNotificationsStore state persists across files.
    • Any future module-scope side effect on an externalized singleton will need another reset line.

Decision needed

  • Convention change. Adopting this breaks "no setup files anywhere" (.agents/docs/architecture/testing-strategy.md, apps/web/AGENTS.md), so those docs need to change.
  • Production code. The i18n.init guard is a test-side monkeypatch here. A cleaner version is an idempotent init in src/services/i18n.ts.
  • Risk. Isolation becomes non-structural: a new test touching new external state can leak again. Mitigations: keep the reset list in one file, run a shuffled seed in CI, and use --isolate as the triage switch (passes isolated but fails shared means a leak).
  • Payoff vs. cost. About 30s saved per full test:coverage run, against a CI job dominated by about 15–18 minutes of e2e.

Alternatives considered

  • Shared-mock refactor of the about 161 files that use vi.mock, so true sharing needs no reset. Rejected: large churn against the documented canonical test shape, for a gain this prototype mostly gets.
  • Moving leaky files to an isolated project. Rejected: the leak depends on file order, not on particular files.
  • Vitest Browser Mode (vitest-browser-react). Not a speed win: the import cost remains and the docs claim fidelity, not speed.
  • Deep imports in libui instead of barrels (@base-ui/react/*, lodash-es/*). Not tried. Would cut per-file import cost while keeping isolation.
  • fsModuleCache. Not measured; transform is only about 3% of web time.
  • For the local loop, scoped runs such as vitest --changed main. These give most of the benefit with no config change.
Ngôn ngữ chính
TypeScript
Star
119
Fork
19
Merge trung bình
1 ngày 18 giờ
Pull request đã merge (30 ngày)
61

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của DouglasNeuroInformatics/OpenDataCapture

Tất cả issue của DouglasNeuroInformatics/OpenDataCapture

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.