Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NativeHeaderToolbar.test.tsx

148 lines5.0 KB

1import type { NativeStackHeaderItem } from "@react-navigation/native-stack";
2import { act, createContext, type ReactElement } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { afterEach, expect, it, vi } from "vite-plus/test";
5​
6type HeaderOptions = {
7 unstable_headerLeftItems?: () => NativeStackHeaderItem[];
8 unstable_headerRightItems?: () => NativeStackHeaderItem[];
9 unstable_headerToolbarItems?: () => NativeStackHeaderItem[];
10};
11​
12const harness = vi.hoisted(() => ({
13 params: { path: ["first", "guide.pdf"] },
14 appliedOptions: {} as HeaderOptions,
15 renderedItems: [] as NativeStackHeaderItem[],
16 setOptionsCalls: 0,
17 openedDocuments: [] as string[],
18}));
19​
20// Native headers retain the actions materialized when navigation applies options. Like React
21// Navigation, the header renders again only when the options are no longer shallowly equal.
22vi.mock("@react-navigation/native", () => {
23 const navigation = {
24 setOptions(options: HeaderOptions) {
25 harness.setOptionsCalls += 1;
26 const previous: Record<string, unknown> = harness.appliedOptions;
27 const next: Record<string, unknown> = { ...previous, ...options };
28 harness.appliedOptions = next;
29 if (
30 Object.keys(next).length === Object.keys(previous).length &&
31 Object.keys(next).every((key) => next[key] === previous[key])
32 )
33 return;
34 harness.renderedItems =
35 options.unstable_headerLeftItems?.() ??
36 options.unstable_headerRightItems?.() ??
37 options.unstable_headerToolbarItems?.() ??
38 [];
39 },
40 };
41 return {
42 useNavigation: () => navigation,
43 useRoute: () => ({ key: "file", name: "ThreadFile", params: harness.params }),
44 };
45});
46​
47import { NativeHeaderToolbar } from "./NativeHeaderToolbar";
48​
49let root: Root | null = null;
50type Placement = "left" | "right" | "bottom";
51​
52function DocumentToolbar(props: { readonly path: string; readonly placement: Placement }) {
53 return (
54 <NativeHeaderToolbar placement={props.placement}>
55 <NativeHeaderToolbar.Menu title="File actions" icon="ellipsis">
56 <NativeHeaderToolbar.MenuAction onPress={() => harness.openedDocuments.push(props.path)}>
57 Open PDF
58 </NativeHeaderToolbar.MenuAction>
59 </NativeHeaderToolbar.Menu>
60 </NativeHeaderToolbar>
61 );
63​
64function renderDocument(path: string, placement: Placement) {
65 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
66 harness.params = { path: path.split("/") };
67 root ??= createRoot(document.createElement("div"));
68 act(() => root!.render(<DocumentToolbar path={path} placement={placement} />));
70​
71// Like React Navigation's NavigationStateContext, whose default value throws when
72// read. React restores a context's default outside render, so layout effects see it.
73const ContainerStateContext = createContext<object>({
74 get getIsInitial(): never {
75 throw new Error("Couldn't find a navigation context.");
76 },
77});
78const containerState = {};
79​
80function ConnectingToolbar(props: { readonly label: string }) {
81 return (
82 <NativeHeaderToolbar placement="right">
83 <NativeHeaderToolbar.Custom>
84 <span aria-label={props.label} />
85 </NativeHeaderToolbar.Custom>
86 </NativeHeaderToolbar>
87 );
89​
90function renderConnecting(label: string) {
91 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
92 root ??= createRoot(document.createElement("div"));
93 act(() =>
94 root!.render(
95 <ContainerStateContext value={containerState}>
96 <ConnectingToolbar label={label} />
97 </ContainerStateContext>,
98 ),
99 );
101​
102function renderedCustomLabel() {
103 const item = harness.renderedItems[0];
104 if (item?.type !== "custom") throw new Error("Expected the custom header element");
105 return (item.element as ReactElement<{ "aria-label": string }>).props["aria-label"];
107​
108function openRenderedDocument() {
109 const menu = harness.renderedItems[0];
110 if (menu?.type !== "menu") throw new Error("Expected the native file menu");
111 const action = menu.menu.items[0];
112 if (action?.type !== "action") throw new Error("Expected the native Open PDF action");
113 action.onPress?.();
115​
116afterEach(() => {
117 act(() => root?.unmount());
118 root = null;
119 harness.appliedOptions = {};
120 harness.renderedItems = [];
121 harness.setOptionsCalls = 0;
122 harness.openedDocuments = [];
123 vi.unstubAllGlobals();
124});
125​
126it.each(["left", "right", "bottom"] as const)(
127 "updates the %s header action when switching between documents with the same name",
128 (placement) => {
129 renderDocument("first/guide.pdf", placement);
130 openRenderedDocument();
131 renderDocument("second/guide.pdf", placement);
132 openRenderedDocument();
133​
134 expect(harness.openedDocuments).toEqual(["first/guide.pdf", "second/guide.pdf"]);
135 },
136);
137​
138it("applies a custom header element rendered inside a navigation container", () => {
139 renderConnecting("Connecting");
140 expect(renderedCustomLabel()).toBe("Connecting");
141​
142 const applied = harness.setOptionsCalls;
143 renderConnecting("Connecting");
144 expect(harness.setOptionsCalls).toBe(applied);
145​
146 renderConnecting("Reconnecting");
147 expect(renderedCustomLabel()).toBe("Reconnecting");
148});