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