const { describe, it, before } = require('node:test'); const assert = require('node:assert'); const express = require('express'); // Pre-populate require.cache so progress routes get mock dependencies // without loading the real index.js (which would start the server) // or the real db.js (which would need sql.js init). const broadcastCalls = []; const mockBroadcast = (payload) => broadcastCalls.push(payload); require.cache[require.resolve('../../index')] = { id: require.resolve('../../index'), filename: require.resolve('../../index'), loaded: true, exports: { broadcast: mockBroadcast }, }; const mockDbRow = { topic: 'math', exercises_done: 5, exercises_correct: 4, last_session: '2024-01-01', notes: '[]' }; require.cache[require.resolve('../../db')] = { id: require.resolve('../../db'), filename: require.resolve('../../db'), loaded: true, exports: { prepare: () => ({ run: () => ({ changes: 1, lastInsertRowid: 1 }), get: () => mockDbRow, all: () => [], }), }, }; const progressRoutes = require('../progress'); function request(app, method, urlPath, body, headers = {}) { return new Promise((resolve, reject) => { const server = app.listen(0, '127.0.0.1', async () => { const port = server.address().port; try { const res = await fetch(`http://127.0.0.1:${port}${urlPath}`, { method, body: body ? JSON.stringify(body) : undefined, headers: { 'Content-Type': 'application/json', ...headers }, }); server.close(() => resolve(res)); } catch (err) { server.close(() => reject(err)); } }); }); } describe('progress routes', () => { let app; before(() => { app = express(); app.use(express.json()); app.use('/api/progress', progressRoutes); }); it('PUT /api/progress/:topic triggers broadcast with progress_update', async () => { broadcastCalls.length = 0; const res = await request(app, 'PUT', '/api/progress/math', { correct: true }); assert.strictEqual(res.status, 200); assert.strictEqual(broadcastCalls.length, 1); assert.strictEqual(broadcastCalls[0].type, 'progress_update'); assert.ok(broadcastCalls[0].data); assert.strictEqual(broadcastCalls[0].data.topic, 'math'); }); });