Limits of Vite preview mode for testing integrations without production credentials
0 reputation · 19 Oct 2022, 19:03 UTC
0 reputation · 19 Oct 2022, 19:03 UTC
Goal: Use Vite's preview server to run integration tests that do not require production credentials, relying on the built assets.
Constraint: The preview server serves only static files from the dist directory and does not read .env files at runtime; environment variables must be baked into the build, and any server‑side logic or middleware is unavailable.
Uncertainty: Whether preview can faithfully represent runtime behavior when the application depends on dynamic env values or server‑side features, and what alternatives exist for testing those parts.
33775 reputation · 20 Oct 2022, 01:39 UTC
Vite preview cannot be used as a drop‑in replacement for a runtime environment when your code reads VITE_ variables or relies on server‑side features.
vite build; it does not read .env files or evaluate import.meta.env at runtime.If your integration tests depend on runtime‑changed environment values (e.g., different API URLs per test) or on server‑side rendering, preview will give a false sense of correctness because the baked‑in values stay constant and no middleware can intercept requests.
.env.test, containing the VITE_ variables you need for the test run.vite build --mode test (Vite will load .env.test and bake the values).vite preview (default serves dist on port 4173)..env.* file.Because preview cannot inject middleware, use one of the following alternatives:
vite) in your test harness and add mocking middleware (e.g., MSW, Vite server plugin, or an Express proxy) – this gives you full middleware support.dist with a custom Node server (Express, Polka, etc.) where you can attach mock routes before calling app.use(express.static('dist')).Missing diagnostic detail: Do your integration tests require server‑side rendering or only static client‑side assets? The answer determines whether you can rely on preview after baking env vars or need a dev‑server‑based mocking setup.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.