Turnpike/frontend/src/sync.test.js

88 lines
2.4 KiB
JavaScript

import { describe, it, expect, beforeEach, vi } from 'vitest'
import { db, getLastSync, setLastSync } from './db.js'
beforeEach(async () => {
await Promise.all(db.tables.map(t => t.clear()))
vi.restoreAllMocks()
})
function mockFetch(body = {}, status = 200) {
globalThis.fetch = vi.fn(() =>
Promise.resolve({
ok: status >= 200 && status < 300,
status,
statusText: 'OK',
json: () => Promise.resolve(body),
})
)
}
describe('syncPull', () => {
it('writes attendees to Dexie', async () => {
mockFetch({
server_time: '2026-03-01T12:00:00Z',
attendees: [{ id: 1, name: 'Titania' }],
departments: [],
volunteers: [],
shifts: [],
volunteer_shifts: [],
})
// Import fresh to reset syncing guard
const { syncPull } = await import('./sync.js')
await syncPull()
const a = await db.attendees.get(1)
expect(a.name).toBe('Titania')
expect(await getLastSync()).toBe('2026-03-01T12:00:00Z')
})
it('deletes soft-deleted attendees from Dexie', async () => {
await db.attendees.put({ id: 1, name: 'Titania' })
mockFetch({
server_time: '2026-03-01T13:00:00Z',
attendees: [{ id: 1, name: 'Titania', deleted_at: '2026-03-01T12:30:00Z' }],
departments: [],
volunteers: [],
shifts: [],
volunteer_shifts: [],
})
const { syncPull } = await import('./sync.js')
await syncPull()
const a = await db.attendees.get(1)
expect(a).toBeUndefined()
})
it('deletes soft-deleted volunteer_shifts from Dexie', async () => {
await db.volunteer_shifts.put({ volunteer_id: 1, shift_id: 2 })
mockFetch({
server_time: '2026-03-01T13:00:00Z',
attendees: [],
departments: [],
volunteers: [],
shifts: [],
volunteer_shifts: [{ volunteer_id: 1, shift_id: 2, deleted_at: '2026-03-01T12:30:00Z' }],
})
const { syncPull } = await import('./sync.js')
await syncPull()
const vs = await db.volunteer_shifts.get([1, 2])
expect(vs).toBeUndefined()
})
it('sets lastSync timestamp', async () => {
mockFetch({
server_time: '2026-03-02T00:00:00Z',
attendees: [],
departments: [],
volunteers: [],
shifts: [],
volunteer_shifts: [],
})
const { syncPull } = await import('./sync.js')
await syncPull()
expect(await getLastSync()).toBe('2026-03-02T00:00:00Z')
})
})