import { test, before, after, beforeEach } from 'node:test'; import assert from 'node:assert/strict'; import { setTestEnv, mockAxiosPost, axiosError, silenceConsole } from './helpers'; setTestEnv({}); const { sendToN8n } = require('../src/services/n8n.service'); let responses: Array<() => any> = []; const calls = mockAxiosPost(async () => { const next = responses.shift(); return next ? next() : { status: 200, data: {} }; }); let capture: ReturnType; before(() => { capture = silenceConsole(); }); after(() => capture.restore()); beforeEach(() => { calls.length = 0; responses = []; }); const fail = (code: string, status?: number) => () => { throw axiosError(code, status); }; test('retries when n8n refuses the connection (n8n restarting)', async () => { responses = [fail('ECONNREFUSED')]; await sendToN8n({ id: 1 }, 'http://n8n.test/status'); assert.equal(calls.length, 2); }); test('retries when the proxy says n8n is down (502/503)', async () => { responses = [fail('ERR_BAD_RESPONSE', 502), fail('ERR_BAD_RESPONSE', 503)]; await sendToN8n({ id: 1 }, 'http://n8n.test/status'); assert.equal(calls.length, 3); }); test('retries 404 while n8n has not registered the webhook yet, up to the max attempts', async () => { responses = [1, 2, 3, 4, 5, 6].map(() => fail('ERR_BAD_REQUEST', 404)); await sendToN8n({ id: 1 }, 'http://n8n.test/status'); assert.equal(calls.length, 5); }); test('does not retry when n8n may already have received the request', async () => { for (const failure of [fail('ECONNABORTED'), fail('ECONNRESET'), fail('ERR_BAD_RESPONSE', 504), fail('ERR_BAD_RESPONSE', 500), fail('ERR_BAD_REQUEST', 400)]) { calls.length = 0; responses = [failure]; await sendToN8n({ id: 1 }, 'http://n8n.test/status'); assert.equal(calls.length, 1); } }); test('sends once when n8n answers', async () => { await sendToN8n({ id: 1 }, 'http://n8n.test/status'); assert.equal(calls.length, 1); });