import axios from 'axios'; import fs from 'fs'; import os from 'os'; import path from 'path'; // Each test file runs in its own process; set env before requiring app modules, // since they read their config at load time. export function setTestEnv(overrides: Record) { delete process.env.TINY_WEBHOOK_SECRET; delete process.env.N8N_WEBHOOK_GRAPHS; delete process.env.GRAPHS_API_URL; delete process.env.NEXSTAR_GRAPHS_API_URL; delete process.env.TINY_LIVE_MAX_QUEUE_WAIT_MS; Object.assign(process.env, { RUNTIME_DATA_DIR: fs.mkdtempSync(path.join(os.tmpdir(), 'tiny-webhook-test-')), TINY_API_TOKEN: 'mock-token', N8N_WEBHOOK_STATUS: 'http://n8n.test/status', TINY_LIVE_REQUEST_DELAY_MS: '0', TINY_LOOKUP_RETRY_DELAY_MS: '5', N8N_RETRY_DELAY_MS: '5', ...overrides }); } export type PostCall = { url: string; data: any }; type PostHandler = (url: string, data: any) => Promise; // Replaces axios.post for the whole process. Returns the recorded calls. export function mockAxiosPost(handler: PostHandler): PostCall[] { const calls: PostCall[] = []; (axios as any).post = async (url: string, data: any) => { calls.push({ url, data }); return handler(url, data); }; return calls; } export function tinyOrder(id: string, overrides: Record = {}) { return { data: { retorno: { status: 'OK', status_processamento: '3', pedido: { id, numero: '140255', numero_ecommerce: '39BAECDB7D', data_pedido: '08/10/2026', data_prevista: '08/10/2026', cliente: { nome: 'Cliente Teste', celular: '(16) 99999-0000', email: 'cliente@test' }, total_pedido: '136.49', id_vendedor: '977231477', nome_vendedor: 'Lais Sousa Da Silva', situacao: 'Pronto para envio', forma_envio: 'X', codigo_rastreamento: '', url_rastreamento: '', itens: [{ item: { codigo: 'BLCS.PTO.G1' } }], ...overrides } } } }; } export function tinyError(codigo: string, erro: string) { return { data: { retorno: { status: 'Erro', codigo_erro: codigo, erros: [{ erro }] } } }; } export function axiosError(code: string, status?: number) { const error: any = new Error(status ? `Request failed with status code ${status}` : code); error.code = code; if (status) error.response = { status, data: {} }; return error; } export const fakeRes = () => ({ status() { return this; }, send() { return this; }, json() { return this; } }) as any; export const orderWebhook = (id: string | number, codigoSituacao: string, descricaoSituacao: string) => ({ query: {}, body: { dados: { id, codigoSituacao, descricaoSituacao } } }) as any; export const isTinyCall = (url: string) => url.includes('api.tiny.com.br'); export function silenceConsole() { const original = { log: console.log, warn: console.warn, error: console.error }; const warnings: string[] = []; console.log = () => {}; console.warn = (...args: any[]) => { warnings.push(args.join(' ')); }; console.error = (...args: any[]) => { warnings.push(args.join(' ')); }; return { warnings, restore: () => Object.assign(console, original) }; }