Open History to see the last commit
1import { act, useEffect, useLayoutEffect, useSyncExternalStore } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5const harness = vi.hoisted(() => {
6 const listeners = new Set<() => void>();
7 const appStateListeners = new Set<(state: string) => void>();
8 const state = { focused: true, appState: "active" };
9 return {
10 state,
11 appStateListeners,
12 subscribe(listener: () => void) {
13 listeners.add(listener);
14 return () => listeners.delete(listener);
15 },
16 setFocused(focused: boolean) {
17 state.focused = focused;
18 for (const listener of listeners) listener();
19 },
20 setAppState(next: string) {
21 state.appState = next;
22 for (const listener of appStateListeners) listener(next);
23 },
24 };
25});
26
27vi.mock("@react-navigation/native", () => ({
28 useIsFocused: () => useSyncExternalStore(harness.subscribe, () => harness.state.focused),
29}));
30vi.mock("react-native", () => ({
31 AppState: {
32 get currentState() {
33 return harness.state.appState;
34 },
35 addEventListener: (_event: "change", listener: (state: string) => void) => {
36 harness.appStateListeners.add(listener);
37 return { remove: () => harness.appStateListeners.delete(listener) };
38 },
39 },
40}));
41
42import { useVisibleSecondClock } from "./use-visible-second-clock";
43
44const START_MS = Date.UTC(2026, 9, 3, 12, 0, 0);
45let root: Root | null = null;
46let renders: number[] = [];
47
48function Probe(props: { readonly enabled: boolean }) {
49 const nowMs = useVisibleSecondClock(props.enabled);
50 useEffect(() => {
51 renders.push(nowMs);
52 });
53 return null;
54}
55
56function mount(enabled: boolean) {
57 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
58 root = createRoot(document.createElement("div"));
59 act(() => root!.render(<Probe enabled={enabled} />));
60}
61
62// One act per second, so each tick commits its own render as it would on device.
63function advance(ms: number) {
64 for (let elapsed = 0; elapsed < ms; elapsed += 1_000) {
65 act(() => vi.advanceTimersByTime(Math.min(1_000, ms - elapsed)));
66 }
67}
68
69function latest() {
70 return renders.at(-1);
71}
72
73beforeEach(() => {
74 vi.useFakeTimers();
75 vi.setSystemTime(START_MS);
76 harness.state.focused = true;
77 harness.state.appState = "active";
78 renders = [];
79});
80
81afterEach(() => {
82 act(() => root?.unmount());
83 root = null;
84 vi.useRealTimers();
85});
86
87describe("useVisibleSecondClock", () => {
88 it("ticks once a second while enabled, focused and active", () => {
89 mount(true);
90 const before = renders.length;
91 advance(60_000);
92 expect(renders.length - before).toBe(60);
93 expect(latest()).toBe(START_MS + 60_000);
94 });
95
96 it("does not wake while the app is in the background", () => {
97 harness.state.appState = "background";
98 mount(true);
99 const before = renders.length;
100 advance(60_000);
101 expect(renders.length - before).toBe(0);
102 expect(vi.getTimerCount()).toBe(0);
103 });
104
105 it("does not wake while the screen is unfocused", () => {
106 harness.state.focused = false;
107 mount(true);
108 const before = renders.length;
109 advance(60_000);
110 expect(renders.length - before).toBe(0);
111 expect(vi.getTimerCount()).toBe(0);
112 });
113
114 it("does not wake when disabled, even when visible", () => {
115 mount(false);
116 const before = renders.length;
117 advance(60_000);
118 expect(renders.length - before).toBe(0);
119 });
120
121 it("notices an AppState change between first render and subscribing", () => {
122 // Layout effects run before the hook's passive subscription, so this change has no listener.
123 function BackgroundBeforeSubscribe() {
124 useLayoutEffect(() => harness.setAppState("background"), []);
125 return null;
126 }
127 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
128 root = createRoot(document.createElement("div"));
129 act(() =>
130 root!.render(
131 <>
132 <BackgroundBeforeSubscribe />
133 <Probe enabled />
134 </>,
135 ),
136 );
137 const before = renders.length;
138 advance(60_000);
139 expect(renders.length - before).toBe(0);
140 expect(vi.getTimerCount()).toBe(0);
141 });
142
143 it("pauses on blur and shows wall-clock elapsed time the moment it refocuses", () => {
144 mount(true);
145 advance(5_000);
146 act(() => harness.setFocused(false));
147 const paused = renders.length;
148 advance(120_000);
149 expect(renders.length).toBe(paused);
150
151 act(() => harness.setFocused(true));
152 expect(latest()).toBe(START_MS + 125_000);
153 advance(1_000);
154 expect(latest()).toBe(START_MS + 126_000);
155 });
156
157 it("pauses while backgrounded and catches up on the first active render", () => {
158 mount(true);
159 act(() => harness.setAppState("background"));
160 const paused = renders.length;
161 advance(600_000);
162 expect(renders.length).toBe(paused);
163 expect(vi.getTimerCount()).toBe(0);
164
165 act(() => harness.setAppState("inactive"));
166 advance(10_000);
167 expect(renders.length).toBe(paused);
168
169 act(() => harness.setAppState("active"));
170 expect(latest()).toBe(START_MS + 610_000);
171 const resumed = renders.length;
172 advance(60_000);
173 expect(renders.length - resumed).toBe(60);
174 });
175
176 it("stops when the work it measures settles and refreshes when new work starts", () => {
177 mount(true);
178 advance(3_000);
179 act(() => root!.render(<Probe enabled={false} />));
180 const settled = renders.length;
181 advance(60_000);
182 expect(renders.length).toBe(settled);
183
184 act(() => root!.render(<Probe enabled />));
185 expect(latest()).toBe(START_MS + 63_000);
186 });
187
188 it("clears its interval and AppState subscription on unmount", () => {
189 mount(true);
190 expect(vi.getTimerCount()).toBe(1);
191 expect(harness.appStateListeners.size).toBe(1);
192 act(() => root!.unmount());
193 root = null;
194 expect(vi.getTimerCount()).toBe(0);
195 expect(harness.appStateListeners.size).toBe(0);
196 });
197});