| 1 | import { describe, it, expect, vi } from 'vitest'
|
| 2 | import request from 'supertest'
|
| 3 | import { NextFunction, Request, Response } from 'express'
|
| 4 | import { createApp } from '@app/createApp'
|
| 5 | import { errorHandler } from '@app/middleware/errorHandler'
|
| 6 | import { DomainError } from '@app/lib/errors/base'
|
| 7 |
|
| 8 | const app = createApp()
|
| 9 |
|
| 10 | function buildRequest() {
|
| 11 | return { log: { error: vi.fn() } }
|
| 12 | }
|
| 13 |
|
| 14 | function buildResponse() {
|
| 15 | return {
|
| 16 | status: vi.fn().mockReturnThis(),
|
| 17 | json: vi.fn().mockReturnThis(),
|
| 18 | }
|
| 19 | }
|
| 20 |
|
| 21 | describe('errorHandler', () => {
|
| 22 | it('returns 500 for an error that reaches it through the app', async () => {
|
| 23 | const res = await request(app)
|
| 24 | .post('/auth/login')
|
| 25 | .set('Content-Type', 'application/json')
|
| 26 | .send('{"email": ')
|
| 27 |
|
| 28 | expect(res.status).toBe(500)
|
| 29 | expect(res.body).toEqual({ error: 'Internal server error' })
|
| 30 | })
|
| 31 |
|
| 32 | it('logs the error through the request logger', () => {
|
| 33 | const req = buildRequest()
|
| 34 | const res = buildResponse()
|
| 35 | const err = new Error('kaboom')
|
| 36 |
|
| 37 | errorHandler(
|
| 38 | err,
|
| 39 | req as unknown as Request,
|
| 40 | res as unknown as Response,
|
| 41 | vi.fn() as unknown as NextFunction,
|
| 42 | )
|
| 43 |
|
| 44 | expect(req.log.error).toHaveBeenCalledWith({ err }, 'request failed')
|
| 45 | expect(res.status).toHaveBeenCalledWith(500)
|
| 46 | })
|
| 47 |
|
| 48 | it('maps domain errors to their status and message', () => {
|
| 49 | const req = buildRequest()
|
| 50 | const res = buildResponse()
|
| 51 |
|
| 52 | errorHandler(
|
| 53 | new DomainError('nope', 409),
|
| 54 | req as unknown as Request,
|
| 55 | res as unknown as Response,
|
| 56 | vi.fn() as unknown as NextFunction,
|
| 57 | )
|
| 58 |
|
| 59 | expect(res.status).toHaveBeenCalledWith(409)
|
| 60 | expect(res.json).toHaveBeenCalledWith({ error: 'nope' })
|
| 61 | })
|
| 62 | })
|