Spaces:
Running
Running
| const test = require('node:test'); | |
| const assert = require('node:assert/strict'); | |
| // Clear cached module to get a fresh in-memory log each run | |
| delete require.cache[require.resolve('../utils/errorLogger')]; | |
| const { logError, getMemoryLog, clearMemoryLog } = require('../utils/errorLogger'); | |
| test('logError stores entry in memory log', () => { | |
| const before = getMemoryLog().length; | |
| const err = new Error('Test database error'); | |
| logError(err, { code: 'TEST_ERROR', statusCode: 500 }); | |
| const log = getMemoryLog(); | |
| assert.equal(log.length, before + 1, 'should append one entry'); | |
| const entry = log[0]; | |
| assert.equal(entry.message, 'Test database error'); | |
| assert.equal(entry.code, 'TEST_ERROR'); | |
| assert.equal(entry.statusCode, 500); | |
| assert.ok(entry.timestamp, 'should have timestamp'); | |
| assert.ok(entry.type, 'should have error type'); | |
| }); | |
| test('logError does not throw with null error', () => { | |
| assert.doesNotThrow(() => logError(null)); | |
| }); | |
| test('logError does not throw with undefined context', () => { | |
| assert.doesNotThrow(() => logError(new Error('bare call'))); | |
| }); | |
| test('logError extracts request context', () => { | |
| const err = new Error('Route error'); | |
| const req = { | |
| originalUrl: '/api/test', | |
| method: 'POST', | |
| ip: '127.0.0.1', | |
| headers: { 'user-agent': 'test-agent' }, | |
| user: { id: 'user-123' }, | |
| body: { title: 'x' }, | |
| }; | |
| logError(err, { req, code: 'REQUEST_FAILED', statusCode: 500 }); | |
| const entry = getMemoryLog()[0]; | |
| assert.equal(entry.request.url, '/api/test'); | |
| assert.equal(entry.request.method, 'POST'); | |
| assert.equal(entry.userId, 'user-123'); | |
| }); | |
| test('clearMemoryLog empties the buffer', () => { | |
| logError(new Error('to clear')); | |
| clearMemoryLog(); | |
| assert.equal(getMemoryLog().length, 0, 'buffer should be empty after clearMemoryLog'); | |
| }); | |
| test('ring buffer is capped at 500 entries', () => { | |
| clearMemoryLog(); | |
| for (let i = 0; i < 510; i++) { | |
| logError(new Error(`error ${i}`)); | |
| } | |
| assert.ok(getMemoryLog().length <= 500, 'buffer must not exceed 500 entries'); | |
| clearMemoryLog(); | |
| }); | |