-
-
Notifications
You must be signed in to change notification settings - Fork 10.9k
Expand file tree
/
Copy pathvite-dev-test.ts
More file actions
575 lines (484 loc) · 17.5 KB
/
Copy pathvite-dev-test.ts
File metadata and controls
575 lines (484 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
import fs from "node:fs/promises";
import path from "node:path";
import { expect } from "@playwright/test";
import dedent from "dedent";
import {
reactRouterConfig,
viteConfig,
test,
type TemplateName,
type Files,
} from "./helpers/vite.js";
const tsx = dedent;
const fixtures = [
{
templateName: "vite-5-template",
v8_viteEnvironmentApi: false,
},
{
templateName: "vite-6-template",
v8_viteEnvironmentApi: true,
},
{
templateName: "vite-8-template",
v8_viteEnvironmentApi: true,
},
{
templateName: "rsc-vite-framework",
v8_viteEnvironmentApi: true,
},
] as const satisfies ReadonlyArray<{
templateName: TemplateName;
v8_viteEnvironmentApi: boolean;
}>;
test.describe("Vite dev", () => {
for (const { templateName, v8_viteEnvironmentApi } of fixtures) {
test.describe(`template: ${templateName} viteEnvironmentApi: ${v8_viteEnvironmentApi}`, () => {
const files: Files = async ({ port }) => ({
"react-router.config.ts": reactRouterConfig({
future: { v8_viteEnvironmentApi },
}),
"vite.config.ts": await viteConfig.basic({
port,
templateName,
mdx: true,
}),
"app/root.tsx": tsx`
import { Links, Meta, Outlet, Scripts } from "react-router";
export default function Root() {
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body>
<div id="content">
<h1>Root</h1>
<Outlet />
</div>
<Scripts />
</body>
</html>
);
}
`,
"app/routes/_index.tsx": tsx`
export default function IndexRoute() {
return (
<div id="index">
<h2 data-title>Index</h2>
<input />
<p data-hmr>HMR updated: no</p>
</div>
);
}
`,
"app/routes/deferred-loader-data.tsx": tsx`
import { Suspense } from "react";
import { Await, useLoaderData } from "react-router";
export function loader() {
let deferred = new Promise((resolve) => {
setTimeout(() => resolve(true), 1000)
});
return { deferred };
}
export default function IndexRoute() {
const { deferred } = useLoaderData<typeof loader>();
return (
<div id="index">
<Suspense fallback={<p data-defer>Defer finished: no</p>}>
<Await resolve={deferred}>{() => <p data-defer>Defer finished: yes</p>}</Await>
</Suspense>
</div>
);
}
`,
"app/routes/set-cookies.tsx": tsx`
import type { LoaderFunction } from "react-router";
export const loader: LoaderFunction = () => {
const headers = new Headers();
headers.append(
"Set-Cookie",
"first=one; Domain=localhost; Path=/; SameSite=Lax"
);
headers.append(
"Set-Cookie",
"second=two; Domain=localhost; Path=/; SameSite=Lax"
);
headers.append(
"Set-Cookie",
"third=three; Domain=localhost; Path=/; SameSite=Lax"
);
headers.set("location", "http://localhost:${port}/get-cookies");
const response = new Response(null, {
headers,
status: 302,
});
return response;
};
`,
"app/routes/get-cookies.tsx": tsx`
import { useLoaderData, type LoaderFunctionArgs } from "react-router";
export const loader = ({ request }: LoaderFunctionArgs) => ({
cookies: request.headers.get("Cookie")
});
export default function IndexRoute() {
const { cookies } = useLoaderData<typeof loader>();
return (
<div id="get-cookies">
<h2 data-title>Get Cookies</h2>
<p data-cookies>{cookies}</p>
</div>
);
}
`,
"app/routes/jsx.jsx": tsx`
export default function JsxRoute() {
return (
<div id="jsx">
<p data-hmr>HMR updated: no</p>
</div>
);
}
`,
"app/routes/mdx.mdx": tsx`
import { useLoaderData } from "react-router";
export const loader = () => {
return {
content: "MDX route content from loader",
}
}
export function MdxComponent() {
const { content } = useLoaderData();
return <div data-mdx-route>{content}</div>
}
## MDX Route
<MdxComponent />
`,
...(!templateName.includes("rsc")
? {
".env": `
ENV_VAR_FROM_DOTENV_FILE=Content from .env file
`,
"app/routes/dotenv.tsx": tsx`
import { useState, useEffect } from "react";
import { useLoaderData } from "react-router";
export const loader = () => {
return {
loaderContent: process.env.ENV_VAR_FROM_DOTENV_FILE,
}
}
export default function DotenvRoute() {
const { loaderContent } = useLoaderData();
const [clientContent, setClientContent] = useState('');
useEffect(() => {
try {
setClientContent("process.env.ENV_VAR_FROM_DOTENV_FILE shouldn't be available on the client, found: " + process.env.ENV_VAR_FROM_DOTENV_FILE);
} catch (err) {
setClientContent("process.env.ENV_VAR_FROM_DOTENV_FILE not available on the client, which is a good thing");
}
}, []);
return <>
<div data-dotenv-route-loader-content>{loaderContent}</div>
<div data-dotenv-route-client-content>{clientContent}</div>
</>
}
`,
}
: {}),
"app/routes/error-stacktrace.tsx": tsx`
import { Link, useLocation, type LoaderFunction, type MetaFunction } from "react-router";
export const loader: LoaderFunction = ({ request }) => {
if (request.url.includes("crash-loader")) {
throw new Error("crash-loader");
}
return null;
};
export default function TestRoute() {
const location = useLocation();
if (import.meta.env.SSR && location.search.includes("crash-server-render")) {
throw new Error("crash-server-render");
}
return (
<div>
<ul>
{["crash-loader", "crash-server-render"].map(
(v) => (
<li key={v}>
<Link to={"/?" + v}>{v}</Link>
</li>
)
)}
</ul>
</div>
);
}
`,
"app/routes/known-route-exports.tsx": tsx`
import { useMatches } from "react-router";
export const meta = () => [{
title: "HMR meta: 0"
}]
export const links = () => [{
rel: "icon",
href: "/favicon.ico",
type: "image/png",
"data-link": "HMR links: 0",
}]
export const handle = {
data: "HMR handle: 0"
};
export default function TestRoute() {
const matches = useMatches();
return (
<div id="known-route-export-hmr">
<input />
<p data-hmr>HMR component: 0</p>
<p data-handle>{matches[1].handle.data}</p>
</div>
);
}
`,
});
test("renders matching routes with HMR", async ({ dev, page }) => {
const { cwd, port } = await dev(files, templateName);
await page.goto(`http://localhost:${port}/`, {
waitUntil: "networkidle",
});
// Ensure no errors on page load
expect(page.errors).toEqual([]);
await expect(page.locator("#index [data-title]")).toHaveText("Index");
let hmrStatus = page.locator("#index [data-hmr]");
await expect(hmrStatus).toHaveText("HMR updated: no");
let input = page.locator("#index input");
await expect(input).toBeVisible();
await input.type("stateful");
let indexRouteContents = await fs.readFile(
path.join(cwd, "app/routes/_index.tsx"),
"utf8",
);
await fs.writeFile(
path.join(cwd, "app/routes/_index.tsx"),
indexRouteContents.replace("HMR updated: no", "HMR updated: yes"),
"utf8",
);
await page.waitForLoadState("networkidle");
await expect(hmrStatus).toHaveText("HMR updated: yes");
await expect(input).toHaveValue("stateful");
// Ensure no errors after HMR
expect(page.errors).toEqual([]);
});
test("deferred loader data", async ({ dev, page }) => {
test.fixme(
templateName.includes("rsc"),
"RSC doesn't support Await component",
);
const { port } = await dev(files, templateName);
await page.goto(`http://localhost:${port}/deferred-loader-data`, {
waitUntil: "networkidle",
});
// Ensure no errors on page load
expect(page.errors).toEqual([]);
await expect(page.locator("#index [data-defer]")).toHaveText(
"Defer finished: yes",
);
// Ensure no errors after deferred rendering
expect(page.errors).toEqual([]);
});
test("handles multiple set-cookie headers", async ({ dev, page }) => {
// TODO(v8): Remove this skip if we no longer support Node 20
test.skip(
templateName.includes("rsc") &&
parseInt(process.versions.node.split(".")[0], 10) === 20,
"vite-plugin-rsc dev cookie handling differs on Node 20.",
);
const { port } = await dev(files, templateName);
await page.goto(`http://localhost:${port}/set-cookies`, {
waitUntil: "networkidle",
});
expect(page.errors).toEqual([]);
// Ensure we redirected
expect(new URL(page.url()).pathname).toBe("/get-cookies");
await expect(page.locator("#get-cookies [data-cookies]")).toHaveText(
"first=one; second=two; third=three",
);
});
test("handles JSX in .jsx file without React import", async ({
dev,
page,
}) => {
const { cwd, port } = await dev(files, templateName);
await page.goto(`http://localhost:${port}/jsx`, {
waitUntil: "networkidle",
});
expect(page.errors).toEqual([]);
let hmrStatus = page.locator("#jsx [data-hmr]");
await expect(hmrStatus).toHaveText("HMR updated: no");
let indexRouteContents = await fs.readFile(
path.join(cwd, "app/routes/jsx.jsx"),
"utf8",
);
await fs.writeFile(
path.join(cwd, "app/routes/jsx.jsx"),
indexRouteContents.replace("HMR updated: no", "HMR updated: yes"),
"utf8",
);
await page.waitForLoadState("networkidle");
await expect(hmrStatus).toHaveText("HMR updated: yes");
expect(page.errors).toEqual([]);
});
test("handles MDX routes", async ({ dev, page }) => {
const { port } = await dev(files, templateName);
await page.goto(`http://localhost:${port}/mdx`, {
waitUntil: "networkidle",
});
expect(page.errors).toEqual([]);
let mdxContent = page.locator("[data-mdx-route]");
await expect(mdxContent).toHaveText("MDX route content from loader");
expect(page.errors).toEqual([]);
});
test("loads .env file", async ({ dev, page }) => {
test.fixme(
templateName.includes("rsc"),
"RSC Framework Mode doesn't load .env files",
);
const { port } = await dev(files, templateName);
await page.goto(`http://localhost:${port}/dotenv`, {
waitUntil: "networkidle",
});
expect(page.errors).toEqual([]);
let loaderContent = page.locator("[data-dotenv-route-loader-content]");
await expect(loaderContent).toHaveText("Content from .env file");
let clientContent = page.locator("[data-dotenv-route-client-content]");
await expect(clientContent).toHaveText(
"process.env.ENV_VAR_FROM_DOTENV_FILE not available on the client, which is a good thing",
);
expect(page.errors).toEqual([]);
});
test("request errors map to original source code", async ({
dev,
page,
}) => {
test.fixme(
templateName.includes("rsc"),
"Investigate this for RSC Framework Mode",
);
const { port } = await dev(files, templateName);
await page.goto(
`http://localhost:${port}/error-stacktrace?crash-server-render`,
);
await expect(page.locator("main")).toContainText(
"Error: crash-server-render",
);
await expect(page.locator("main")).toContainText(
"error-stacktrace.tsx:14:11",
);
await page.goto(
`http://localhost:${port}/error-stacktrace?crash-loader`,
);
await expect(page.locator("main")).toContainText("Error: crash-loader");
await expect(page.locator("main")).toContainText(
"error-stacktrace.tsx:5:11",
);
});
test("handle known route exports with HMR", async ({ dev, page }) => {
test.fixme(
templateName.includes("rsc"),
"Investigate why this is failing in RSC Framework Mode",
);
const { cwd, port } = await dev(files, templateName);
await page.goto(`http://localhost:${port}/known-route-exports`, {
waitUntil: "networkidle",
});
expect(page.errors).toEqual([]);
// file editing utils
let filepath = path.join(cwd, "app/routes/known-route-exports.tsx");
let filedata = await fs.readFile(filepath, "utf8");
async function editFile(edit: (data: string) => string) {
filedata = edit(filedata);
await fs.writeFile(filepath, filedata, "utf8");
}
// verify input state is preserved after each update
let input = page.locator("input");
await input.type("stateful");
await expect(input).toHaveValue("stateful");
// component
await editFile((data) =>
data.replace("HMR component: 0", "HMR component: 1"),
);
await expect(page.locator("[data-hmr]")).toHaveText("HMR component: 1");
await expect(input).toHaveValue("stateful");
// handle
await editFile((data) =>
data.replace("HMR handle: 0", "HMR handle: 1"),
);
await expect(page.locator("[data-handle]")).toHaveText("HMR handle: 1");
await expect(input).toHaveValue("stateful");
// meta
await editFile((data) => data.replace("HMR meta: 0", "HMR meta: 1"));
await expect(page).toHaveTitle("HMR meta: 1");
await expect(input).toHaveValue("stateful");
// links
await editFile((data) => data.replace("HMR links: 0", "HMR links: 1"));
await expect(page.locator("[data-link]")).toHaveAttribute(
"data-link",
"HMR links: 1",
);
expect(page.errors).toEqual([]);
});
});
}
test("does not prebundle RSC server-only route imports in the client optimizer", async ({
page,
dev,
}) => {
let files: Files = async ({ port }) => ({
"react-router.config.ts": reactRouterConfig({
future: { unstable_optimizeDeps: true },
}),
"vite.config.ts": await viteConfig.basic({
port,
templateName: "rsc-vite-framework",
}),
"app/routes/_index.tsx": tsx`
import { readServerSecret } from "rsc-server-only-package";
export async function loader() {
return { secret: readServerSecret() };
}
export default function IndexRoute() {
return <h1 data-route>Index route</h1>;
}
`,
"node_modules/rsc-server-only-package/package.json": JSON.stringify({
name: "rsc-server-only-package",
version: "1.0.0",
type: "module",
main: "index.js",
}),
"node_modules/rsc-server-only-package/index.js": tsx`
export function readServerSecret() {
return "server-only";
}
`,
});
let { cwd, port } = await dev(files, "rsc-vite-framework");
await page.goto(`http://localhost:${port}/`);
await expect(page.locator("[data-route]")).toHaveText("Index route");
let metadataPath = path.join(cwd, "node_modules/.vite/deps/_metadata.json");
await expect
.poll(async () => {
try {
return await fs.readFile(metadataPath, "utf8");
} catch {
return "";
}
})
.not.toBe("");
let clientDeps = [
await fs.readFile(metadataPath, "utf8"),
...(await fs.readdir(path.dirname(metadataPath))),
].join("\n");
expect(clientDeps).not.toMatch(/rsc[-_]server[-_]only[-_]package/);
});
});