import { initDatabase, insertMeasurement, getAllMeasurements, getLatestMeasurement, updateMeasurement } from '../src/database/db' import { Measurement } from '../src/types' import * as SQLite from 'expo-sqlite' jest.mock('expo-sqlite', () => ({ openDatabaseAsync: jest.fn(), })) const mockMeasurement: Measurement = { id: '550e8400-e29b-41d4-a716-446655440000', weight: 75.5, bmi: 22.3, bodyFatPercentage: 15.2, fatMass: 11.5, musclePercentage: 40.1, muscleMass: 30.3, visceralFat: 8, bmr: 1650, measuredAt: '2024-01-01T08:00:00.000Z', createdAt: '2024-01-01T08:00:00.000Z', updatedAt: '2024-01-01T08:00:00.000Z', syncStatus: 'local', } describe('database', () => { let db: any beforeEach(() => { db = { execAsync: jest.fn(), runAsync: jest.fn(), getAllAsync: jest.fn(), } ;(SQLite.openDatabaseAsync as jest.Mock).mockResolvedValue(db) }) it('initDatabase creates the measurements table', async () => { await initDatabase() expect(db.execAsync).toHaveBeenCalledWith( expect.stringContaining('CREATE TABLE IF NOT EXISTS measurements') ) }) it('insertMeasurement inserts a row', async () => { db.runAsync.mockResolvedValue(undefined) await initDatabase() await insertMeasurement(mockMeasurement) expect(db.runAsync).toHaveBeenCalledWith( expect.stringContaining('INSERT INTO measurements'), expect.arrayContaining([mockMeasurement.id]) ) }) it('getAllMeasurements returns all measurements ordered by measuredAt desc', async () => { db.getAllAsync.mockResolvedValue([{ ...mockMeasurement }]) await initDatabase() const result = await getAllMeasurements() expect(result).toHaveLength(1) expect(result[0].id).toBe(mockMeasurement.id) }) it('getLatestMeasurement returns the most recent', async () => { db.getAllAsync.mockResolvedValue([{ ...mockMeasurement }]) await initDatabase() const result = await getLatestMeasurement() expect(result).not.toBeNull() expect(result!.id).toBe(mockMeasurement.id) }) it('updateMeasurement updates syncStatus', async () => { db.runAsync.mockResolvedValue(undefined) await initDatabase() await updateMeasurement(mockMeasurement.id, 'synced') expect(db.runAsync).toHaveBeenCalledWith( expect.stringContaining('UPDATE measurements'), expect.arrayContaining(['synced', mockMeasurement.id]) ) }) })