|
| 1 | +import { describe, expect, it } from 'vitest'; |
| 2 | +import type { FastifyReply, FastifyRequest } from '../../../src/integrations/fastify/types'; |
| 3 | +import { defaultShouldHandleError } from '../../../src/integrations/fastify/utils'; |
| 4 | + |
| 5 | +const request: FastifyRequest = { method: 'POST', routeOptions: { url: '/' } }; |
| 6 | + |
| 7 | +function reply(statusCode: number): FastifyReply { |
| 8 | + return { statusCode } as FastifyReply; |
| 9 | +} |
| 10 | + |
| 11 | +function errorWith(props: { statusCode?: number; status?: number }): Error { |
| 12 | + return Object.assign(new Error('test error'), props); |
| 13 | +} |
| 14 | + |
| 15 | +describe('defaultShouldHandleError', () => { |
| 16 | + // Fastify runs `onError` hooks before it applies the error's status to the reply, |
| 17 | + // e.g. for a body that fails to parse, so `reply.statusCode` is still the default 200 there. |
| 18 | + describe('when the reply status has not been set yet', () => { |
| 19 | + it('skips errors carrying a 4xx `statusCode`', () => { |
| 20 | + expect(defaultShouldHandleError(errorWith({ statusCode: 400 }), request, reply(200))).toBe(false); |
| 21 | + }); |
| 22 | + |
| 23 | + it('skips errors carrying a 4xx `status`', () => { |
| 24 | + expect(defaultShouldHandleError(errorWith({ status: 404 }), request, reply(200))).toBe(false); |
| 25 | + }); |
| 26 | + |
| 27 | + it('skips errors carrying a 4xx status as a string', () => { |
| 28 | + expect( |
| 29 | + defaultShouldHandleError(Object.assign(new Error('test error'), { statusCode: '404' }), request, reply(200)), |
| 30 | + ).toBe(false); |
| 31 | + }); |
| 32 | + |
| 33 | + it('captures errors carrying a 5xx status', () => { |
| 34 | + expect(defaultShouldHandleError(errorWith({ statusCode: 503 }), request, reply(200))).toBe(true); |
| 35 | + }); |
| 36 | + |
| 37 | + it('captures errors without a status', () => { |
| 38 | + expect(defaultShouldHandleError(new Error('test error'), request, reply(200))).toBe(true); |
| 39 | + }); |
| 40 | + |
| 41 | + it('captures errors carrying a status below 400, which Fastify sends as a 500', () => { |
| 42 | + expect(defaultShouldHandleError(errorWith({ statusCode: 302 }), request, reply(200))).toBe(true); |
| 43 | + }); |
| 44 | + }); |
| 45 | + |
| 46 | + describe('when the reply status has been set', () => { |
| 47 | + it('skips errors on a 4xx reply', () => { |
| 48 | + expect(defaultShouldHandleError(new Error('test error'), request, reply(404))).toBe(false); |
| 49 | + }); |
| 50 | + |
| 51 | + it('skips errors on a 3xx reply', () => { |
| 52 | + expect(defaultShouldHandleError(new Error('test error'), request, reply(302))).toBe(false); |
| 53 | + }); |
| 54 | + |
| 55 | + it('captures errors on a 5xx reply', () => { |
| 56 | + expect(defaultShouldHandleError(errorWith({ statusCode: 400 }), request, reply(500))).toBe(true); |
| 57 | + }); |
| 58 | + }); |
| 59 | +}); |
0 commit comments