🧪 Test timezone helpers and local collections
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { all, closeDb, get, openDb, pendingCount, remove, save, status, syncNow, toRecord, update } from './db.svelte';
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const server = new Map<string, Map<string, Record<string, unknown>>>();
|
||||
const pushes: { collection: string; id: string; data: Record<string, unknown>; client_updated_at: number; deleted: boolean }[] = [];
|
||||
const batches: number[] = [];
|
||||
let tick = 0;
|
||||
return {
|
||||
server,
|
||||
pushes,
|
||||
batches,
|
||||
stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ')
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('$lib/pb', () => ({
|
||||
pb: {
|
||||
autoCancellation: () => undefined,
|
||||
filter: (tpl: string, params: Record<string, unknown>) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))),
|
||||
collection: (name: string) => ({
|
||||
getFullList: async () => [...(mocks.server.get(name)?.values() ?? [])],
|
||||
subscribe: async () => async () => undefined
|
||||
}),
|
||||
send: async (path: string, options: { method?: string; body?: unknown }) => {
|
||||
if (path !== '/api/sync/push' || options.method !== 'POST') return {};
|
||||
const body = options.body as { changes: (typeof mocks.pushes)[number][] };
|
||||
mocks.batches.push(body.changes.length);
|
||||
const results = body.changes.map((c) => {
|
||||
const record = { id: c.id, ...c.data, client_updated_at: c.client_updated_at, rev: 1, deleted: c.deleted, updated: mocks.stamp() };
|
||||
let store = mocks.server.get(c.collection);
|
||||
if (!store) {
|
||||
store = new Map();
|
||||
mocks.server.set(c.collection, store);
|
||||
}
|
||||
store.set(c.id, record);
|
||||
mocks.pushes.push(c);
|
||||
return { id: c.id, collection: c.collection, status: 'ok', record };
|
||||
});
|
||||
return { results };
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
let n = 0;
|
||||
const settingsRow = { effective_from: '2026-01-01', hours_per_week: 40, workdays_mask: 31, timezone: 'UTC' };
|
||||
|
||||
beforeEach(async () => {
|
||||
status.online = false;
|
||||
await openDb(`user-${++n}`);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await closeDb();
|
||||
});
|
||||
|
||||
describe('local collections', () => {
|
||||
it('save assigns a 15 char id and all returns the record', async () => {
|
||||
const id = await save('balance_adjustments', null, { delta_ms: 1000, note: 'overtime', effective_at: 5 });
|
||||
expect(id).toMatch(/^[a-z0-9]{15}$/);
|
||||
const rows = all('balance_adjustments');
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({ id, delta_ms: 1000, note: 'overtime', effective_at: 5, deleted: false, rev: 0, updated: '' });
|
||||
expect(get('balance_adjustments', id)?.note).toBe('overtime');
|
||||
expect(get('balance_adjustments', 'nope')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('update patches the data and bumps client_updated_at', async () => {
|
||||
const id = await save('settings_history', null, settingsRow);
|
||||
const before = get('settings_history', id)?.client_updated_at ?? 0;
|
||||
await update('settings_history', id, { hours_per_week: 32.5 });
|
||||
const row = get('settings_history', id);
|
||||
expect(row).toMatchObject({ hours_per_week: 32.5, workdays_mask: 31, timezone: 'UTC', deleted: false });
|
||||
expect(row?.client_updated_at).toBeGreaterThanOrEqual(before + 1);
|
||||
});
|
||||
|
||||
it('remove hides a record from all but keeps it as deleted', async () => {
|
||||
const id = await save('entries', null, { start_time: 1, end_time: 2, auto_stopped: false, note: '', day_key: '2026-01-01' });
|
||||
await remove('entries', id);
|
||||
expect(all('entries')).toHaveLength(0);
|
||||
expect(all('entries', true)).toHaveLength(1);
|
||||
expect(all('entries', true)[0]).toMatchObject({ id, deleted: true });
|
||||
expect(get('entries', id)?.deleted).toBe(true);
|
||||
});
|
||||
|
||||
it('data survives closeDb and a second openDb', async () => {
|
||||
const uid = `user-${n}`;
|
||||
const id = await save('settings_history', null, settingsRow);
|
||||
await closeDb();
|
||||
expect(status.ready).toBe(false);
|
||||
expect(all('settings_history')).toEqual([]);
|
||||
await openDb(uid);
|
||||
expect(all('settings_history')).toHaveLength(1);
|
||||
expect(get('settings_history', id)?.hours_per_week).toBe(40);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sync boundary', () => {
|
||||
it('toRecord turns end_time 0 into null and coerces the metadata', () => {
|
||||
const doc = toRecord('entries', {
|
||||
id: 'abc',
|
||||
owner: 'u1',
|
||||
start_time: '10',
|
||||
end_time: 0,
|
||||
auto_stopped: 1,
|
||||
note: null,
|
||||
day_key: '2026-01-01',
|
||||
client_updated_at: '7',
|
||||
rev: null,
|
||||
deleted: false,
|
||||
updated: 123,
|
||||
created: 'x'
|
||||
});
|
||||
expect(doc).toEqual({
|
||||
id: 'abc',
|
||||
start_time: 10,
|
||||
end_time: null,
|
||||
auto_stopped: true,
|
||||
note: '',
|
||||
day_key: '2026-01-01',
|
||||
client_updated_at: 7,
|
||||
rev: 0,
|
||||
deleted: false,
|
||||
updated: '123'
|
||||
});
|
||||
});
|
||||
|
||||
it('toRecord keeps 0 in fields that are not zero-means-null', () => {
|
||||
expect(toRecord('balance_adjustments', { id: 'a', delta_ms: 0, note: '', effective_at: 0 }).delta_ms).toBe(0);
|
||||
expect(toRecord('entries', { id: 'a', start_time: 0, end_time: 5, auto_stopped: false, note: '', day_key: '' }).start_time).toBe(0);
|
||||
});
|
||||
|
||||
it('a sync round pushes end_time null as 0 and pulls 0 back as null', async () => {
|
||||
status.online = true;
|
||||
await save('entries', null, { start_time: 1000, end_time: null, auto_stopped: false, note: 'run', day_key: '1970-01-01' });
|
||||
expect(pendingCount()).toBe(1);
|
||||
await syncNow();
|
||||
expect(pendingCount()).toBe(0);
|
||||
const pushed = mocks.pushes.filter((c) => c.collection === 'entries');
|
||||
expect(pushed).toHaveLength(1);
|
||||
expect(pushed[0].data).toEqual({ start_time: 1000, end_time: 0, auto_stopped: false, note: 'run', day_key: '1970-01-01' });
|
||||
expect(pushed[0].deleted).toBe(false);
|
||||
const row = all('entries')[0];
|
||||
expect(row).toMatchObject({ start_time: 1000, end_time: null, note: 'run', deleted: false, rev: 1 });
|
||||
expect(row.updated).not.toBe('');
|
||||
expect(localStorage.getItem(`wotra-cursor:user-${n}:entries`)).not.toBeNull();
|
||||
expect(status.error).toBeNull();
|
||||
});
|
||||
|
||||
it('a sync round pushes in batches below the server limit', async () => {
|
||||
status.online = true;
|
||||
mocks.batches.length = 0;
|
||||
for (let i = 0; i < 250; i++) {
|
||||
await save('balance_adjustments', null, { delta_ms: i + 1, note: '', effective_at: i });
|
||||
}
|
||||
await syncNow();
|
||||
expect(pendingCount()).toBe(0);
|
||||
expect(mocks.batches.length).toBeGreaterThan(1);
|
||||
expect(Math.max(...mocks.batches)).toBeLessThanOrEqual(200);
|
||||
expect(mocks.batches.reduce((sum, size) => sum + size, 0)).toBe(250);
|
||||
}, 20000);
|
||||
});
|
||||
Reference in New Issue
Block a user