-
-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathfetcher-test.ts
528 lines (456 loc) · 18.5 KB
/
fetcher-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
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
import { expect, test } from "@playwright/test";
import {
createAppFixture,
createFixture,
js,
} from "./helpers/create-fixture.js";
import type { Fixture, AppFixture } from "./helpers/create-fixture.js";
import { PlaywrightFixture } from "./helpers/playwright-fixture.js";
test.describe("useFetcher", () => {
let fixture: Fixture;
let appFixture: AppFixture;
let CHEESESTEAK = "CHEESESTEAK";
let LUNCH = "LUNCH";
let PARENT_LAYOUT_LOADER = "parent layout loader";
let PARENT_LAYOUT_ACTION = "parent layout action";
let PARENT_INDEX_LOADER = "parent index loader";
let PARENT_INDEX_ACTION = "parent index action";
test.beforeAll(async () => {
fixture = await createFixture({
files: {
"app/routes/resource-route-action-only.ts": js`
import { json } from "react-router";
export function action() {
return new Response("${CHEESESTEAK}");
}
`,
"app/routes/fetcher-action-only-call.tsx": js`
import { useFetcher } from "react-router";
export default function FetcherActionOnlyCall() {
let fetcher = useFetcher();
let executeFetcher = () => {
fetcher.submit(new URLSearchParams(), {
method: 'post',
action: '/resource-route-action-only',
});
};
return (
<>
<button id="fetcher-submit" onClick={executeFetcher}>Click Me</button>
{fetcher.data && <pre>{fetcher.data}</pre>}
</>
);
}
`,
"app/routes/resource-route.tsx": js`
export function loader() {
return new Response("${LUNCH}");
}
export function action() {
return new Response("${CHEESESTEAK}");
}
`,
"app/routes/_index.tsx": js`
import { useFetcher } from "react-router";
export default function Index() {
let fetcher = useFetcher();
return (
<>
<fetcher.Form action="/resource-route">
<button type="submit" formMethod="get">get</button>
<button type="submit" formMethod="post">post</button>
</fetcher.Form>
<button id="fetcher-load" type="button" onClick={() => {
fetcher.load('/resource-route');
}}>
load
</button>
<button id="fetcher-submit" type="button" onClick={() => {
fetcher.submit(new URLSearchParams(), {
method: 'post',
action: '/resource-route'
});
}}>
submit
</button>
<pre>{fetcher.data}</pre>
</>
);
}
`,
"app/routes/parent.tsx": js`
import { Outlet } from "react-router";
export function action() {
return new Response("${PARENT_LAYOUT_ACTION}");
};
export function loader() {
return new Response("${PARENT_LAYOUT_LOADER}");
};
export default function Parent() {
return <Outlet />;
}
`,
"app/routes/parent._index.tsx": js`
import { useFetcher } from "react-router";
export function action() {
return new Response("${PARENT_INDEX_ACTION}");
};
export function loader() {
return new Response("${PARENT_INDEX_LOADER}");
};
export default function ParentIndex() {
let fetcher = useFetcher();
return (
<>
<pre>{fetcher.data}</pre>
<button id="load-parent" onClick={() => fetcher.load('/parent')}>
Load parent
</button>
<button id="load-index" onClick={() => fetcher.load('/parent?index')}>
Load index
</button>
<button id="submit-empty" onClick={() => fetcher.submit({})}>
Submit empty
</button>
<button id="submit-parent-get" onClick={() => fetcher.submit({}, { method: 'get', action: '/parent' })}>
Submit parent
</button>
<button id="submit-index-get" onClick={() => fetcher.submit({}, { method: 'get', action: '/parent?index' })}>
Submit index
</button>
<button id="submit-parent-post" onClick={() => fetcher.submit({}, { method: 'post', action: '/parent' })}>
Submit parent
</button>
<button id="submit-index-post" onClick={() => fetcher.submit({}, { method: 'post', action: '/parent?index' })}>
Submit index
</button>
</>
);
}
`,
"app/routes/fetcher-echo.tsx": js`
import { useFetcher } from "react-router";
export async function action({ request }) {
await new Promise(r => setTimeout(r, 1000));
let contentType = request.headers.get('Content-Type');
let value;
if (contentType.includes('application/json')) {
let json = await request.json();
value = json === null ? json : json.value;
} else if (contentType.includes('text/plain')) {
value = await request.text();
} else {
value = (await request.formData()).get('value');
}
return { data: "ACTION (" + contentType + ") " + value }
}
export async function loader({ request }) {
await new Promise(r => setTimeout(r, 1000));
let value = new URL(request.url).searchParams.get('value');
return { data: "LOADER " + value }
}
export default function Index() {
let fetcherValues = [];
if (typeof window !== 'undefined') {
if (!window.fetcherValues) {
window.fetcherValues = [];
}
fetcherValues = window.fetcherValues
}
let fetcher = useFetcher();
let currentValue = fetcher.state + '/' + fetcher.data?.data;
if (fetcherValues[fetcherValues.length - 1] !== currentValue) {
fetcherValues.push(currentValue)
}
return (
<>
<input id="fetcher-input" name="value" />
<button id="fetcher-load" onClick={() => {
let value = document.getElementById('fetcher-input').value;
fetcher.load('/fetcher-echo?value=' + value)
}}>Load</button>
<button id="fetcher-submit" onClick={() => {
let value = document.getElementById('fetcher-input').value;
fetcher.submit({ value }, { method: 'post', action: '/fetcher-echo' })
}}>Submit</button>
<button id="fetcher-submit-json" onClick={() => {
let value = document.getElementById('fetcher-input').value;
fetcher.submit({ value }, { method: 'post', action: '/fetcher-echo', encType: 'application/json' })
}}>Submit JSON</button>
<button id="fetcher-submit-json-null" onClick={() => {
fetcher.submit(null, { method: 'post', action: '/fetcher-echo', encType: 'application/json' })
}}>Submit Null JSON</button>
<button id="fetcher-submit-text" onClick={() => {
let value = document.getElementById('fetcher-input').value;
fetcher.submit(value, { method: 'post', action: '/fetcher-echo', encType: 'text/plain' })
}}>Submit Text</button>
<button id="fetcher-submit-text-empty" onClick={() => {
fetcher.submit("", { method: 'post', action: '/fetcher-echo', encType: 'text/plain' })
}}>Submit Empty Text</button>
{fetcher.state === 'idle' ? <p id="fetcher-idle">IDLE</p> : null}
<pre>{JSON.stringify(fetcherValues)}</pre>
</>
);
}
`,
},
});
appFixture = await createAppFixture(fixture);
});
test.afterAll(() => {
appFixture.close();
});
test.describe("No JavaScript", () => {
test.use({ javaScriptEnabled: false });
test("Form can hit a loader", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/");
await Promise.all([
page.waitForNavigation(),
app.clickSubmitButton("/resource-route", {
wait: false,
method: "get",
}),
]);
// Check full HTML here - Chromium/Firefox/Webkit seem to render this in
// a <pre> but Edge puts it in some weird code editor markup:
// <body data-code-mirror="Readonly code editor.">
// <div hidden="true">"LUNCH"</div>
expect(await app.getHtml()).toContain(LUNCH);
});
test("Form can hit an action", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/");
await Promise.all([
page.waitForNavigation({ waitUntil: "load" }),
app.clickSubmitButton("/resource-route", {
wait: false,
method: "post",
}),
]);
// Check full HTML here - Chromium/Firefox/Webkit seem to render this in
// a <pre> but Edge puts it in some weird code editor markup:
// <body data-code-mirror="Readonly code editor.">
// <div hidden="true">"LUNCH"</div>
expect(await app.getHtml()).toContain(CHEESESTEAK);
});
});
test("load can hit a loader", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/");
await app.clickElement("#fetcher-load");
await page.waitForSelector(`pre:has-text("${LUNCH}")`);
});
test("submit can hit an action", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/");
await app.clickElement("#fetcher-submit");
await page.waitForSelector(`pre:has-text("${CHEESESTEAK}")`);
});
test("submit can hit an action with json", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/fetcher-echo", true);
await page.fill("#fetcher-input", "input value");
await app.clickElement("#fetcher-submit-json");
await page.waitForSelector(`#fetcher-idle`);
expect(await app.getHtml()).toMatch(
'ACTION (application/json) input value"'
);
});
test("submit can hit an action with null json", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/fetcher-echo", true);
await app.clickElement("#fetcher-submit-json-null");
await new Promise((r) => setTimeout(r, 1000));
await page.waitForSelector(`#fetcher-idle`);
expect(await app.getHtml()).toMatch('ACTION (application/json) null"');
});
test("submit can hit an action with text", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/fetcher-echo", true);
await page.fill("#fetcher-input", "input value");
await app.clickElement("#fetcher-submit-text");
await page.waitForSelector(`#fetcher-idle`);
expect(await app.getHtml()).toMatch(
'ACTION (text/plain;charset=UTF-8) input value"'
);
});
test("submit can hit an action with empty text", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/fetcher-echo", true);
await app.clickElement("#fetcher-submit-text-empty");
await new Promise((r) => setTimeout(r, 1000));
await page.waitForSelector(`#fetcher-idle`);
expect(await app.getHtml()).toMatch('ACTION (text/plain;charset=UTF-8) "');
});
test("submit can hit an action only route", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/fetcher-action-only-call");
await app.clickElement("#fetcher-submit");
await page.waitForSelector(`pre:has-text("${CHEESESTEAK}")`);
});
test("fetchers handle ?index param correctly", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/parent");
await app.clickElement("#load-parent");
await page.waitForSelector(`pre:has-text("${PARENT_LAYOUT_LOADER}")`);
await app.clickElement("#load-index");
await page.waitForSelector(`pre:has-text("${PARENT_INDEX_LOADER}")`);
// fetcher.submit({}) defaults to GET for the current Route
await app.clickElement("#submit-empty");
await page.waitForSelector(`pre:has-text("${PARENT_INDEX_LOADER}")`);
await app.clickElement("#submit-parent-get");
await page.waitForSelector(`pre:has-text("${PARENT_LAYOUT_LOADER}")`);
await app.clickElement("#submit-index-get");
await page.waitForSelector(`pre:has-text("${PARENT_INDEX_LOADER}")`);
await app.clickElement("#submit-parent-post");
await page.waitForSelector(`pre:has-text("${PARENT_LAYOUT_ACTION}")`);
await app.clickElement("#submit-index-post");
await page.waitForSelector(`pre:has-text("${PARENT_INDEX_ACTION}")`);
});
test("fetcher.load persists data through reloads", async ({ page }) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/fetcher-echo", true);
expect(await app.getHtml("pre")).toMatch(
JSON.stringify(["idle/undefined"])
);
await page.fill("#fetcher-input", "1");
await app.clickElement("#fetcher-load");
await page.waitForSelector("#fetcher-idle");
expect(await app.getHtml("pre")).toMatch(
JSON.stringify(["idle/undefined", "loading/undefined", "idle/LOADER 1"])
);
await page.fill("#fetcher-input", "2");
await app.clickElement("#fetcher-load");
await page.waitForSelector("#fetcher-idle");
expect(await app.getHtml("pre")).toMatch(
JSON.stringify([
"idle/undefined",
"loading/undefined",
"idle/LOADER 1",
"loading/LOADER 1", // Preserves old data during reload
"idle/LOADER 2",
])
);
});
test("fetcher.submit persists data through resubmissions", async ({
page,
}) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/fetcher-echo", true);
expect(await app.getHtml("pre")).toMatch(
JSON.stringify(["idle/undefined"])
);
await page.fill("#fetcher-input", "1");
await app.clickElement("#fetcher-submit");
await page.waitForSelector("#fetcher-idle");
expect(await app.getHtml("pre")).toMatch(
JSON.stringify([
"idle/undefined",
"submitting/undefined",
"loading/ACTION (application/x-www-form-urlencoded;charset=UTF-8) 1",
"idle/ACTION (application/x-www-form-urlencoded;charset=UTF-8) 1",
])
);
await page.fill("#fetcher-input", "2");
await app.clickElement("#fetcher-submit");
await page.waitForSelector("#fetcher-idle");
expect(await app.getHtml("pre")).toMatch(
JSON.stringify([
"idle/undefined",
"submitting/undefined",
"loading/ACTION (application/x-www-form-urlencoded;charset=UTF-8) 1",
"idle/ACTION (application/x-www-form-urlencoded;charset=UTF-8) 1",
// Preserves old data during resubmissions
"submitting/ACTION (application/x-www-form-urlencoded;charset=UTF-8) 1",
"loading/ACTION (application/x-www-form-urlencoded;charset=UTF-8) 2",
"idle/ACTION (application/x-www-form-urlencoded;charset=UTF-8) 2",
])
);
});
});
test.describe("fetcher aborts and adjacent forms", () => {
let fixture: Fixture;
let appFixture: AppFixture;
test.beforeAll(async () => {
fixture = await createFixture({
files: {
"app/routes/_index.tsx": js`
import * as React from "react";
import {
Form,
useFetcher,
useLoaderData,
useNavigation
} from "react-router";
export async function loader({ request }) {
// 1 second timeout on data
await new Promise((r) => setTimeout(r, 1000));
return { foo: 'bar' };
}
export default function Index() {
const [open, setOpen] = React.useState(true);
const { data } = useLoaderData();
const navigation = useNavigation();
return (
<div>
{navigation.state === 'idle' && <div id="idle">Idle</div>}
<Form id="main-form">
<input id="submit-form" type="submit" />
</Form>
<button id="open" onClick={() => setOpen(true)}>Show async form</button>
{open && <Child onClose={() => setOpen(false)} />}
</div>
);
}
function Child({ onClose }) {
const fetcher = useFetcher();
return (
<fetcher.Form method="get" action="/api">
<button id="submit-fetcher" type="submit">Trigger fetcher (shows a message)</button>
<button
type="submit"
form="main-form"
id="submit-and-close"
onClick={() => setTimeout(onClose, 250)}
>
Submit main form and close async form
</button>
</fetcher.Form>
);
}
`,
"app/routes/api.tsx": js`
export async function loader() {
await new Promise((resolve) => setTimeout(resolve, 500));
return { message: 'Hello world!' }
}
`,
},
});
appFixture = await createAppFixture(fixture);
});
test.afterAll(() => {
appFixture.close();
});
test("Unmounting a fetcher does not cancel the request of an adjacent form", async ({
page,
}) => {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/");
// Works as expected before the fetcher is loaded
// submit the main form and unmount the fetcher form
await app.clickElement("#submit-and-close");
// Wait for our navigation state to be "Idle"
await page.waitForSelector("#idle", { timeout: 2000 });
// Breaks after the fetcher is loaded
// re-mount the fetcher form
await app.clickElement("#open");
// submit the fetcher form
await app.clickElement("#submit-fetcher");
// submit the main form and unmount the fetcher form
await app.clickElement("#submit-and-close");
// Wait for navigation state to be "Idle"
await page.waitForSelector("#idle", { timeout: 2000 });
});
});