-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathOfflineSyncManager.test.ts
More file actions
92 lines (77 loc) · 2.65 KB
/
OfflineSyncManager.test.ts
File metadata and controls
92 lines (77 loc) · 2.65 KB
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
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { OfflineSyncManager } from '../OfflineSyncManager';
describe('OfflineSyncManager (Microservices Architecture)', () => {
let originalFetch: typeof global.fetch;
let fetchMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
// Mock localStorage
const store: Record<string, string> = {};
vi.stubGlobal('localStorage', {
getItem: vi.fn((key: string) => store[key] || null),
setItem: vi.fn((key: string, value: string) => {
store[key] = value;
}),
clear: vi.fn(() => {
for (const key in store) delete store[key];
}),
});
// Mock navigator online status
vi.stubGlobal('navigator', { onLine: false });
// Mock fetch
originalFetch = global.fetch;
fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 });
global.fetch = fetchMock;
});
afterEach(() => {
vi.restoreAllMocks();
global.fetch = originalFetch;
});
it('queues requests when offline', () => {
const manager = new OfflineSyncManager();
manager.enqueueRequest({
targetService: 'groups',
endpoint: '/api/groups/123/messages',
method: 'POST',
body: { text: 'Hello offline!' },
});
// Since it's offline, fetch should not have been called
expect(fetchMock).not.toHaveBeenCalled();
// Check if it saved to localStorage
expect(localStorage.setItem).toHaveBeenCalledWith(
'teachlink_offline_queue_v1',
expect.stringContaining('Hello offline!'),
);
});
it('processes queue and routes to correct microservice when back online', async () => {
const manager = new OfflineSyncManager({
serviceUrls: {
groups: 'https://groups.microservice.local',
courses: 'https://courses.microservice.local',
auth: '',
users: '',
certificates: '',
},
});
// Enqueue while offline
manager.enqueueRequest({
targetService: 'groups',
endpoint: '/messages',
method: 'POST',
body: { text: 'Group msg' },
});
manager.enqueueRequest({
targetService: 'courses',
endpoint: '/progress',
method: 'PUT',
body: { courseId: 'c1', progress: 50 },
});
// Simulate coming back online
vi.stubGlobal('navigator', { onLine: true });
window.dispatchEvent(new Event('online'));
// Wait for async processing
await new Promise(process.nextTick);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock.mock.calls[0][0]).toBe('https://groups.microservice.local/messages');
expect(fetchMock.mock.calls[1][0]).toBe('https://courses.microservice.local/progress');
});
});