aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/client/stores/sync.test.tsx
blob: fee79d7592c59a7c75b97cc4fa0c97323fa17f14 (plain)
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
/**
 * @vitest-environment jsdom
 */
import "fake-indexeddb/auto";
import { act, renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "../db/index";
import { SyncProvider, useSync } from "./sync";

// Mock fetch globally
const mockFetch = vi.fn();
global.fetch = mockFetch;

// Mock apiClient
vi.mock("../api/client", () => ({
	apiClient: {
		getAuthHeader: vi.fn(() => ({ Authorization: "Bearer token" })),
	},
}));

const wrapper = ({ children }: { children: ReactNode }) => (
	<SyncProvider>{children}</SyncProvider>
);

describe("useSync", () => {
	beforeEach(async () => {
		vi.clearAllMocks();
		localStorage.clear();
		await db.decks.clear();
		await db.cards.clear();
		await db.reviewLogs.clear();

		// Default mock for fetch
		mockFetch.mockResolvedValue({
			ok: true,
			json: async () => ({
				decks: [],
				cards: [],
				reviewLogs: [],
				noteTypes: [],
				noteFieldTypes: [],
				notes: [],
				noteFieldValues: [],
				conflicts: {
					decks: [],
					cards: [],
					noteTypes: [],
					noteFieldTypes: [],
					notes: [],
					noteFieldValues: [],
				},
				currentSyncVersion: 0,
			}),
		});
	});

	afterEach(async () => {
		vi.restoreAllMocks();
		localStorage.clear();
		await db.decks.clear();
		await db.cards.clear();
		await db.reviewLogs.clear();
	});

	it("throws error when used outside SyncProvider", () => {
		// Suppress console.error for this test
		const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});

		expect(() => {
			renderHook(() => useSync());
		}).toThrow("useSync must be used within a SyncProvider");

		consoleSpy.mockRestore();
	});

	it("returns initial state", async () => {
		const { result } = renderHook(() => useSync(), { wrapper });

		await waitFor(() => {
			expect(result.current.isOnline).toBe(true);
			expect(result.current.isSyncing).toBe(false);
			expect(result.current.pendingCount).toBe(0);
			expect(result.current.lastSyncAt).toBeNull();
			expect(result.current.lastError).toBeNull();
			expect(result.current.status).toBe("idle");
		});
	});

	it("provides sync function", async () => {
		const { result } = renderHook(() => useSync(), { wrapper });

		await waitFor(() => {
			expect(typeof result.current.sync).toBe("function");
		});
	});

	it("updates isSyncing during sync", async () => {
		// Make the sync take some time
		mockFetch.mockImplementation(
			() =>
				new Promise((resolve) =>
					setTimeout(
						() =>
							resolve({
								ok: true,
								json: async () => ({
									decks: [],
									cards: [],
									reviewLogs: [],
									conflicts: { decks: [], cards: [] },
									currentSyncVersion: 0,
								}),
							}),
						50,
					),
				),
		);

		const { result } = renderHook(() => useSync(), { wrapper });

		await waitFor(() => {
			expect(result.current.isSyncing).toBe(false);
		});

		// Start sync
		let syncPromise: Promise<unknown>;
		act(() => {
			syncPromise = result.current.sync();
		});

		// Check that isSyncing becomes true
		await waitFor(() => {
			expect(result.current.isSyncing).toBe(true);
		});

		// Wait for sync to complete
		await act(async () => {
			await syncPromise;
		});

		expect(result.current.isSyncing).toBe(false);
	});

	it("updates lastSyncAt after successful sync", async () => {
		mockFetch.mockResolvedValue({
			ok: true,
			json: async () => ({
				decks: [],
				cards: [],
				reviewLogs: [],
				noteTypes: [],
				noteFieldTypes: [],
				notes: [],
				noteFieldValues: [],
				conflicts: {
					decks: [],
					cards: [],
					noteTypes: [],
					noteFieldTypes: [],
					notes: [],
					noteFieldValues: [],
				},
				currentSyncVersion: 1,
			}),
		});

		const { result } = renderHook(() => useSync(), { wrapper });

		await waitFor(() => {
			expect(result.current.lastSyncAt).toBeNull();
		});

		await act(async () => {
			await result.current.sync();
		});

		await waitFor(() => {
			expect(result.current.lastSyncAt).not.toBeNull();
		});
	});

	it("updates lastError on sync failure", async () => {
		mockFetch.mockResolvedValue({
			ok: false,
			status: 500,
			json: async () => ({ error: "Server error" }),
		});

		const { result } = renderHook(() => useSync(), { wrapper });

		await waitFor(() => {
			expect(result.current.lastError).toBeNull();
		});

		await act(async () => {
			await result.current.sync();
		});

		await waitFor(() => {
			expect(result.current.lastError).toBe("Server error");
			expect(result.current.status).toBe("error");
		});
	});

	it("responds to online/offline events", async () => {
		const { result } = renderHook(() => useSync(), { wrapper });

		await waitFor(() => {
			expect(result.current.isOnline).toBe(true);
		});

		// Simulate going offline
		act(() => {
			window.dispatchEvent(new Event("offline"));
		});

		await waitFor(() => {
			expect(result.current.isOnline).toBe(false);
		});

		// Simulate going online
		act(() => {
			window.dispatchEvent(new Event("online"));
		});

		await waitFor(() => {
			expect(result.current.isOnline).toBe(true);
		});
	});
});