-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.test.tsx
352 lines (286 loc) · 10.3 KB
/
index.test.tsx
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
/* eslint-disable functional/prefer-immutable-types */
/* eslint-disable functional/no-return-void */
/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable functional/immutable-data */
/* eslint-disable functional/no-expression-statements */
/* eslint-disable functional/functional-parameters */
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { wrapRouter } from ".";
import { act, cleanup, render, waitFor } from "@testing-library/react";
import React from "react";
// Polyfill for fetch and global Request required by react-router.
import "whatwg-fetch";
beforeEach(() => {
// Avoid `Error: Not implemented: window.scrollTo`
window.scrollTo = () => {};
// oaf-react-router has a side-effect of manipulating document title (i.e. global mutable state).
window.document.title = "";
});
afterEach(cleanup);
const setTimeoutPromise = () =>
new Promise((resolve) => setTimeout(() => resolve(undefined)));
describe("oaf-react-router", () => {
test("doesn't throw when wrapping and unwrapping a browser router", () => {
const router = createBrowserRouter([
{
path: "/",
element: <div>Hello world!</div>,
},
]);
const unwrap = wrapRouter(router, { documentTitle: () => "test title c" });
render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
expect(() => unwrap()).not.toThrow();
});
test("disables native scroll restoration", () => {
const router = createBrowserRouter([{}]);
expect(window.history.scrollRestoration).toBeUndefined();
const unwrap = wrapRouter(router, { disableAutoScrollRestoration: true });
expect(window.history.scrollRestoration).toEqual("manual");
unwrap();
expect(window.history.scrollRestoration).toBeUndefined();
});
test("sets the document title after initial render", async () => {
const router = createBrowserRouter([{}]);
wrapRouter(router, {
setPageTitle: true,
documentTitle: () => "test title b",
});
expect(document.title).toBe("");
await waitFor(() => expect(document.title).toBe("test title b"));
});
test("sets the document title after a navigation", async () => {
const router = createBrowserRouter([{}]);
wrapRouter(router, {
setPageTitle: true,
documentTitle: () => "test title a",
});
expect(document.title).toBe("");
await router.navigate("/");
// Prove that `delay(settings.renderTimeout)` is putting the title update on the end of the event loop.
expect(document.title).toBe("");
await setTimeoutPromise();
// Now, after waiting, we should have updated the page title.
await waitFor(() => expect(document.title).toBe("test title a"));
});
test("does not set the document title when setPageTitle is false", async () => {
const router = createBrowserRouter([{}]);
wrapRouter(router, {
setPageTitle: false,
documentTitle: () => "shouldn't happen",
});
expect(document.title).toBe("");
await router.navigate("/");
// We can't just use waitFor with a negative condition that we expect to _remain_ negative after setTimeouts have been allowed to run.
await setTimeoutPromise();
await waitFor(() => expect(document.title).toBe(""));
});
test("leaves focus alone when repairFocus is false", async () => {
const router = createBrowserRouter([{}]);
// Given a router wrapper that is set to NOT repair focus.
wrapRouter(router, { repairFocus: false });
// and given a default focus target (an h1 element within main).
render(
<React.StrictMode>
<main>
<h1></h1>
<button></button>
</main>
</React.StrictMode>,
);
// And another arbitrary element that happens to currently have focus.
document.querySelector("button")?.focus();
expect(document.activeElement).toBe(document.querySelector("button"));
// When we navigate using a wrapped router.
await router.navigate("/");
// Then focus remains on the previously focused element.
await waitFor(() =>
expect(document.activeElement).toBe(document.querySelector("button")),
);
});
test("moves focus to body when primary focus target cannot be focused", async () => {
const router = createBrowserRouter([
{
path: "/",
element: (
<main>
<h1></h1>
<button></button>
</main>
),
},
]);
wrapRouter(router);
// Given a default focus target (an h1 element within main)...
render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
// ...that cannot receive focus (because we sabotaged it)
const h1 = document.querySelector("h1");
expect(h1).toBeDefined();
// eslint-disable-next-line functional/no-conditional-statements
if (h1 !== null) {
h1.focus = () => {};
}
// And another arbitrary element that happens to currently have focus.
document.querySelector("button")?.focus();
expect(document.activeElement).toBe(document.querySelector("button"));
// When we navigate using a wrapped router.
await act(() => router.navigate("/"));
// Then the wrapper falls back on focusing the body or document
// element when it fails to focus the (sabotaged) H1.
await waitFor(() =>
expect([document.body, document.documentElement]).toContain(
document.activeElement,
),
);
});
test("moves focus to the primary focus target and announce navigation to screen readers", async () => {
// Given a default focus target (an h1 element within main).
const router = createBrowserRouter([
{
path: "/",
element: <div />,
loader: () => Promise.resolve(null),
},
{
path: "/hello",
element: (
<main>
<h1></h1>
<button></button>
</main>
),
// The presence of these loaders means that the router will emit loading states before it
// emits idle states (at the completion of the overarching navigation event).
// We only want to update document title, repair focus, announce navigation to screen reader users after
// the final idle state, never in response to the intermediary loading state.
loader: () => Promise.resolve(null),
},
]);
// And a mocked announce function.
const mockAnnounce = jest.fn(function (this: unknown) {
return Promise.resolve(undefined);
});
wrapRouter(router, {
announce: mockAnnounce,
});
render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
// And given focus is currently on the body or the document.
expect(document.activeElement).toBe(document.documentElement);
// When we navigate using a wrapped router.
await act(() => router.navigate({ pathname: "/hello" }));
// Then the wrapper causes focus to move to that default focus target.
await waitFor(() => expect(document.activeElement).not.toBeNull());
await waitFor(() =>
expect(document.activeElement).toBe(document.querySelector("h1")),
);
// And a screen reader announcement was made only for the `idle` state, not the `loading` state.
expect(mockAnnounce.mock.calls).toHaveLength(1);
});
test("restores focus after a POP navigation", async () => {
// Given a route.
const router = createBrowserRouter([
{
path: "/one",
element: (
<main>
<h1>Page one</h1>
<button></button>
</main>
),
},
{
path: "/two",
element: (
<main>
<h1>Page two</h1>
</main>
),
},
{
path: "*",
element: <div>Not found</div>,
},
]);
// And a wrapped router that restores page state on pop.
wrapRouter(router, { restorePageStateOnPop: true });
render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
// And given we have previously focused the button.
await act(() => router.navigate({ pathname: "/one" }));
const button = document.querySelector("button");
// eslint-disable-next-line functional/no-conditional-statements
if (button === null) {
// eslint-disable-next-line functional/no-throw-statements
throw new Error("Expected button not found in DOM");
}
button.focus();
expect(document.activeElement).toBe(button);
// And then navigated away.
await act(() => router.navigate({ pathname: "/two" }));
// And then waited for React to render.
await waitFor(() =>
setTimeoutPromise().then(() =>
expect(document.querySelector("h1")).not.toBeNull(),
),
);
expect(document.activeElement).toBe(document.querySelector("h1"));
// When we navigate back (POP).
await act(() => router.navigate(-1));
// And wait for React to render.
await waitFor(() =>
setTimeoutPromise().then(() =>
expect(document.querySelector("button")).not.toBeNull(),
),
);
// Then focus has been moved back to the button.
expect(document.activeElement).toBe(document.querySelector("button"));
});
test("stops making changes after unsubscribing", async () => {
// Given a router.
const router = createBrowserRouter([
{
path: "*",
element: <div />,
},
]);
// And a mocked announce function.
const mockAnnounce = jest.fn(function (this: unknown) {
return Promise.resolve(undefined);
});
// And a wrapped router.
const unsubscribe = wrapRouter(router, {
announce: mockAnnounce,
});
render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
// When we navigate.
await act(() => router.navigate({ pathname: "/" }));
// Then the navigation is announced.
await waitFor(() => expect(mockAnnounce.mock.calls).toHaveLength(1));
// But when we unsubscribe.
unsubscribe();
// And navigate again.
await act(() => router.navigate({ pathname: "/" }));
// We can't just use waitFor with a negative condition that we expect to _remain_ negative after setTimeouts have been allowed to run.
await setTimeoutPromise();
// Then no more announcements are made.
expect(mockAnnounce.mock.calls).toHaveLength(1);
});
});