|
| 1 | +import { createServer } from 'http'; |
| 2 | +import axios from 'axios'; |
| 3 | +import { |
| 4 | + afterAll, |
| 5 | + afterEach, |
| 6 | + beforeAll, |
| 7 | + beforeEach, |
| 8 | + describe, |
| 9 | + expect, |
| 10 | + test, |
| 11 | + vi, |
| 12 | +} from 'vitest'; |
| 13 | + |
| 14 | +import handler from '@/pages/api/cnpj/v1/[cnpj]'; |
| 15 | +import { getCnpjData } from '@/services/cnpj'; |
| 16 | + |
| 17 | +const unavailable = { |
| 18 | + message: 'Serviço de consulta de CNPJ temporariamente indisponível.', |
| 19 | + name: 'ServiceUnavailableError', |
| 20 | + type: 'service_unavailable', |
| 21 | +}; |
| 22 | + |
| 23 | +function providerError(status, code) { |
| 24 | + return new axios.AxiosError( |
| 25 | + 'Private provider error', |
| 26 | + code, |
| 27 | + { url: 'https://minhareceita.org/private' }, |
| 28 | + {}, |
| 29 | + status ? { status, data: { message: 'Mensagem do provedor.' } } : undefined |
| 30 | + ); |
| 31 | +} |
| 32 | + |
| 33 | +let server; |
| 34 | +let url; |
| 35 | + |
| 36 | +beforeAll(async () => { |
| 37 | + // Use the real app/error/cache/CORS middleware, with only the provider mocked. |
| 38 | + server = createServer((request, response) => { |
| 39 | + request.query = { cnpj: '00000000000000' }; |
| 40 | + response.status = (status) => { |
| 41 | + response.statusCode = status; |
| 42 | + return response; |
| 43 | + }; |
| 44 | + response.json = (data) => { |
| 45 | + response.setHeader('Content-Type', 'application/json'); |
| 46 | + response.end(JSON.stringify(data)); |
| 47 | + return response; |
| 48 | + }; |
| 49 | + handler(request, response); |
| 50 | + }); |
| 51 | + await new Promise((resolve) => { |
| 52 | + server.listen(0, '127.0.0.1', resolve); |
| 53 | + }); |
| 54 | + url = `http://127.0.0.1:${server.address().port}/api/cnpj/v1/00000000000000`; |
| 55 | +}); |
| 56 | + |
| 57 | +afterAll(async () => { |
| 58 | + if (!server) return; |
| 59 | + await new Promise((resolve, reject) => { |
| 60 | + server.close((error) => (error ? reject(error) : resolve())); |
| 61 | + server.closeAllConnections(); |
| 62 | + }); |
| 63 | +}); |
| 64 | + |
| 65 | +beforeEach(() => { |
| 66 | + vi.spyOn(axios, 'get'); |
| 67 | + vi.spyOn(console, 'log').mockImplementation(() => {}); |
| 68 | +}); |
| 69 | + |
| 70 | +afterEach(() => { |
| 71 | + vi.useRealTimers(); |
| 72 | + vi.restoreAllMocks(); |
| 73 | +}); |
| 74 | + |
| 75 | +describe('CNPJ provider failure contract', () => { |
| 76 | + test('preserves the successful status, payload, CORS and cache policy', async () => { |
| 77 | + const data = { |
| 78 | + cnpj: '00000000000000', |
| 79 | + razao_social: 'EMPRESA DE TESTE', |
| 80 | + capital_social: 0, |
| 81 | + qsa: [], |
| 82 | + porte: null, |
| 83 | + }; |
| 84 | + axios.get.mockResolvedValue({ status: 200, data }); |
| 85 | + |
| 86 | + const response = await fetch(url); |
| 87 | + |
| 88 | + expect(response.status).toBe(200); |
| 89 | + expect(await response.json()).toEqual(data); |
| 90 | + expect(response.headers.get('access-control-allow-origin')).toBe('*'); |
| 91 | + expect(response.headers.get('cache-control')).toContain('s-maxage=86400'); |
| 92 | + expect(axios.get).toHaveBeenCalledExactlyOnceWith( |
| 93 | + 'https://minhareceita.org/00000000000000', |
| 94 | + { timeout: 5000, signal: expect.any(AbortSignal) } |
| 95 | + ); |
| 96 | + }); |
| 97 | + |
| 98 | + test('keeps CORS preflight independent of provider availability', async () => { |
| 99 | + const response = await fetch(url, { |
| 100 | + method: 'OPTIONS', |
| 101 | + headers: { |
| 102 | + Origin: 'https://example.com', |
| 103 | + 'Access-Control-Request-Method': 'GET', |
| 104 | + }, |
| 105 | + }); |
| 106 | + |
| 107 | + expect(response.status).toBe(204); |
| 108 | + expect(response.headers.get('access-control-allow-origin')).toBe('*'); |
| 109 | + expect(axios.get).not.toHaveBeenCalled(); |
| 110 | + }); |
| 111 | + |
| 112 | + test('keeps unexpected errors as 500 through the error middleware', async () => { |
| 113 | + axios.get.mockRejectedValue(new TypeError('Unexpected error')); |
| 114 | + |
| 115 | + const response = await fetch(url); |
| 116 | + |
| 117 | + expect(response.status).toBe(500); |
| 118 | + expect(await response.json()).toEqual({ |
| 119 | + message: 'Unexpected error', |
| 120 | + name: 'TypeError', |
| 121 | + type: 'internal_error', |
| 122 | + }); |
| 123 | + }); |
| 124 | + |
| 125 | + test.each([ |
| 126 | + [400, 'BadRequestError', 'bad_request'], |
| 127 | + [404, 'NotFoundError', 'not_found'], |
| 128 | + ])('preserves provider %s responses', async (status, name, type) => { |
| 129 | + axios.get.mockRejectedValue(providerError(status)); |
| 130 | + |
| 131 | + const response = await fetch(url); |
| 132 | + |
| 133 | + expect(response.status).toBe(status); |
| 134 | + expect(await response.json()).toEqual({ |
| 135 | + message: 'Mensagem do provedor.', |
| 136 | + name, |
| 137 | + type, |
| 138 | + }); |
| 139 | + }); |
| 140 | + |
| 141 | + test.each([500, 502, 503, 504, 599])( |
| 142 | + 'maps provider %s to a non-cacheable, sanitized 503', |
| 143 | + async (status) => { |
| 144 | + axios.get.mockRejectedValue(providerError(status)); |
| 145 | + |
| 146 | + const response = await fetch(url); |
| 147 | + |
| 148 | + expect(response.status).toBe(503); |
| 149 | + expect(await response.json()).toEqual(unavailable); |
| 150 | + expect(response.headers.get('cache-control')).toBe('no-store'); |
| 151 | + expect(response.headers.get('access-control-allow-origin')).toBe('*'); |
| 152 | + expect(axios.get).toHaveBeenCalledTimes(1); |
| 153 | + } |
| 154 | + ); |
| 155 | + |
| 156 | + test.each(['ECONNABORTED', 'ETIMEDOUT', 'ECONNRESET', 'ENOTFOUND'])( |
| 157 | + 'maps transport failure %s to 503', |
| 158 | + async (code) => { |
| 159 | + axios.get.mockRejectedValue(providerError(undefined, code)); |
| 160 | + |
| 161 | + const response = await fetch(url); |
| 162 | + |
| 163 | + expect(response.status).toBe(503); |
| 164 | + expect(await response.json()).toEqual(unavailable); |
| 165 | + expect(response.headers.get('cache-control')).toBe('no-store'); |
| 166 | + } |
| 167 | + ); |
| 168 | + |
| 169 | + test.each([401, 403, 429, 600])( |
| 170 | + 'does not reclassify other provider status %s as unavailable', |
| 171 | + async (status) => { |
| 172 | + const error = providerError(status); |
| 173 | + axios.get.mockRejectedValue(error); |
| 174 | + await expect(getCnpjData('00000000000000')).rejects.toBe(error); |
| 175 | + } |
| 176 | + ); |
| 177 | + |
| 178 | + test.each([ |
| 179 | + new TypeError('Unexpected error'), |
| 180 | + new axios.AxiosError('Invalid configuration', 'ERR_BAD_OPTION'), |
| 181 | + ])( |
| 182 | + 'does not disguise programming/configuration errors: %s', |
| 183 | + async (error) => { |
| 184 | + axios.get.mockRejectedValue(error); |
| 185 | + await expect(getCnpjData('00000000000000')).rejects.toBe(error); |
| 186 | + } |
| 187 | + ); |
| 188 | + |
| 189 | + test('aborts a stalled connection after 5 seconds and clears the deadline', async () => { |
| 190 | + vi.useFakeTimers(); |
| 191 | + axios.get.mockImplementation( |
| 192 | + (providerUrl, { signal }) => |
| 193 | + new Promise((resolve, reject) => { |
| 194 | + signal.addEventListener('abort', () => { |
| 195 | + reject(new axios.CanceledError('canceled')); |
| 196 | + }); |
| 197 | + }) |
| 198 | + ); |
| 199 | + const request = getCnpjData('00000000000000').catch((error) => error); |
| 200 | + const { signal } = axios.get.mock.calls[0][1]; |
| 201 | + |
| 202 | + await vi.advanceTimersByTimeAsync(4999); |
| 203 | + expect(signal.aborted).toBe(false); |
| 204 | + await vi.advanceTimersByTimeAsync(1); |
| 205 | + await expect(request).resolves.toMatchObject({ |
| 206 | + status: 503, |
| 207 | + ...unavailable, |
| 208 | + }); |
| 209 | + expect(signal.aborted).toBe(true); |
| 210 | + expect(vi.getTimerCount()).toBe(0); |
| 211 | + }); |
| 212 | + |
| 213 | + test.each([true, false])( |
| 214 | + 'clears the deadline on settled requests: %s', |
| 215 | + async (success) => { |
| 216 | + vi.useFakeTimers(); |
| 217 | + if (success) axios.get.mockResolvedValue({ status: 200, data: {} }); |
| 218 | + else axios.get.mockRejectedValue(providerError(404)); |
| 219 | + |
| 220 | + await getCnpjData('00000000000000').catch(() => {}); |
| 221 | + |
| 222 | + expect(vi.getTimerCount()).toBe(0); |
| 223 | + expect(axios.get.mock.calls[0][1].signal.aborted).toBe(false); |
| 224 | + } |
| 225 | + ); |
| 226 | +}); |
0 commit comments