-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathvite-dev-test.ts
442 lines (370 loc) · 13.5 KB
/
vite-dev-test.ts
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
import { test, expect } from "@playwright/test";
import type { Readable } from "node:stream";
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import fs from "node:fs/promises";
import path from "node:path";
import resolveBin from "resolve-bin";
import getPort from "get-port";
import waitOn from "wait-on";
import { createFixtureProject, js } from "./helpers/create-fixture.js";
import { killtree } from "./helpers/killtree.js";
test.describe("Vite dev", () => {
let projectDir: string;
let devProc: ChildProcessWithoutNullStreams;
let devPort: number;
test.beforeAll(async () => {
devPort = await getPort();
projectDir = await createFixtureProject({
compiler: "vite",
files: {
"remix.config.js": js`
throw new Error("Remix should not access remix.config.js when using Vite");
export default {};
`,
"vite.config.ts": js`
import { defineConfig } from "vite";
import { unstable_vitePlugin as remix } from "@remix-run/dev";
import mdx from "@mdx-js/rollup";
export default defineConfig({
server: {
port: ${devPort},
strictPort: true,
},
plugins: [
remix(),
mdx(),
],
});
`,
"app/root.tsx": js`
import { Links, Meta, Outlet, Scripts, LiveReload } from "@remix-run/react";
export default function Root() {
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body>
<div id="content">
<h1>Root</h1>
<Outlet />
</div>
<Scripts />
<LiveReload nonce="1234" />
</body>
</html>
);
}
`,
"app/routes/_index.tsx": js`
import { Suspense } from "react";
import { defer } from "@remix-run/node";
import { Await, useLoaderData } from "@remix-run/react";
export function loader() {
let deferred = new Promise((resolve) => {
setTimeout(() => resolve(true), 1000)
});
return defer({ deferred });
}
export default function IndexRoute() {
const { deferred } = useLoaderData<typeof loader>();
return (
<div id="index">
<h2 data-title>Index</h2>
<input />
<p data-hmr>HMR updated: no</p>
<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": js`
import { LoaderFunction } from "@remix-run/node";
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:${devPort}/get-cookies");
const response = new Response(null, {
headers,
status: 302,
});
return response;
};
`,
"app/routes/get-cookies.tsx": js`
import { json, LoaderFunctionArgs } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react"
export const loader = ({ request }: LoaderFunctionArgs) => json({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": js`
export default function JsxRoute() {
return (
<div id="jsx">
<p data-hmr>HMR updated: no</p>
</div>
);
}
`,
"app/routes/mdx.mdx": js`
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
export const loader = () => {
return json({
content: "MDX route content from loader",
})
}
export function MdxComponent() {
const { content } = useLoaderData();
return <div data-mdx-route>{content}</div>
}
## MDX Route
<MdxComponent />
`,
".env": `
ENV_VAR_FROM_DOTENV_FILE=Content from .env file
`,
"app/routes/dotenv.tsx": js`
import { useState, useEffect } from "react";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
export const loader = () => {
return json({
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/known-route-exports.tsx": js`
import { useMatches } from "@remix-run/react";
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>
);
}
`,
},
});
let nodeBin = process.argv[0];
let viteBin = resolveBin.sync("vite");
devProc = spawn(nodeBin, [viteBin, "dev"], {
cwd: projectDir,
env: process.env,
stdio: "pipe",
});
let devStdout = bufferize(devProc.stdout);
let devStderr = bufferize(devProc.stderr);
await waitOn({
resources: [`http://localhost:${devPort}/`],
timeout: 10000,
}).catch((err) => {
let stdout = devStdout();
let stderr = devStderr();
throw new Error(
[
err.message,
"",
"exit code: " + devProc.exitCode,
"stdout: " + stdout ? `\n${stdout}\n` : "<empty>",
"stderr: " + stderr ? `\n${stderr}\n` : "<empty>",
].join("\n")
);
});
});
test.afterAll(async () => {
devProc.pid && (await killtree(devProc.pid));
});
test("renders matching routes", async ({ page }) => {
let pageErrors: unknown[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
await page.goto(`http://localhost:${devPort}/`, {
waitUntil: "networkidle",
});
// Ensure no errors on page load
expect(pageErrors).toEqual([]);
await expect(page.locator("#index [data-title]")).toHaveText("Index");
await expect(page.locator("#index [data-defer]")).toHaveText(
"Defer finished: yes"
);
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(projectDir, "app/routes/_index.tsx"),
"utf8"
);
await fs.writeFile(
path.join(projectDir, "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");
// check LiveReload script has nonce
await expect(page.locator(`script[nonce="1234"]`)).toBeAttached();
// Ensure no errors after HMR
expect(pageErrors).toEqual([]);
});
test("handles multiple set-cookie headers", async ({ page }) => {
let pageErrors: Error[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
await page.goto(`http://localhost:${devPort}/set-cookies`, {
waitUntil: "networkidle",
});
expect(pageErrors).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 ({ page }) => {
let pageErrors: unknown[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
await page.goto(`http://localhost:${devPort}/jsx`, {
waitUntil: "networkidle",
});
expect(pageErrors).toEqual([]);
let hmrStatus = page.locator("#jsx [data-hmr]");
await expect(hmrStatus).toHaveText("HMR updated: no");
let indexRouteContents = await fs.readFile(
path.join(projectDir, "app/routes/jsx.jsx"),
"utf8"
);
await fs.writeFile(
path.join(projectDir, "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(pageErrors).toEqual([]);
});
test("handles MDX routes", async ({ page }) => {
let pageErrors: unknown[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
await page.goto(`http://localhost:${devPort}/mdx`, {
waitUntil: "networkidle",
});
expect(pageErrors).toEqual([]);
let mdxContent = page.locator("[data-mdx-route]");
await expect(mdxContent).toHaveText("MDX route content from loader");
expect(pageErrors).toEqual([]);
});
test("loads .env file", async ({ page }) => {
let pageErrors: unknown[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
await page.goto(`http://localhost:${devPort}/dotenv`, {
waitUntil: "networkidle",
});
expect(pageErrors).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(pageErrors).toEqual([]);
});
test("handle known route exports with HMR", async ({ page }) => {
let pageErrors: unknown[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
await page.goto(`http://localhost:${devPort}/known-route-exports`, {
waitUntil: "networkidle",
});
expect(pageErrors).toEqual([]);
// file editing utils
let filepath = path.join(projectDir, "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(pageErrors).toEqual([]);
});
});
let bufferize = (stream: Readable): (() => string) => {
let buffer = "";
stream.on("data", (data) => (buffer += data.toString()));
return () => buffer;
};