import { afterEach, describe, expect, it } from 'bun:test'; import { createCheckoutPreference, isPublicHttpsUrl, searchMpPaymentByExternalReference } from '@/modules/mp/lib/mp-http'; describe('isPublicHttpsUrl', () => { it('only asks Mercado Pago for the automatic return on public HTTPS', () => { expect(isPublicHttpsUrl('https://app.gruperly.com/student/payments')).toBe(true); expect(isPublicHttpsUrl('http://localhost:6173/student/payments')).toBe(false); expect(isPublicHttpsUrl('https://localhost:6173/student/payments')).toBe(false); expect(isPublicHttpsUrl('http://app.gruperly.com/student/payments')).toBe(false); expect(isPublicHttpsUrl('not a url')).toBe(false); }); }); describe('createCheckoutPreference', () => { const realFetch = globalThis.fetch; afterEach(() => { globalThis.fetch = realFetch; }); async function sentBody(input: { backUrl: string; notificationUrl?: string }) { let body: Record = {}; globalThis.fetch = (async (_url: string, init: RequestInit) => { body = JSON.parse(String(init.body)); return new Response(JSON.stringify({ id: 'pref-1', init_point: 'https://mp/pay' }), { status: 201 }); }) as unknown as typeof fetch; await createCheckoutPreference('token', { title: 'Octubre', unitPrice: 100, currencyId: 'ARS', externalReference: 'pay-1', ...input, }); return body; } it('asks for the automatic return and the notification on public HTTPS', async () => { const body = await sentBody({ backUrl: 'https://app.gruperly.com/student/payments', notificationUrl: 'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks', }); expect(body.auto_return).toBe('approved'); expect(body.notification_url).toBe( 'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks', ); }); it('leaves both out on localhost, which Mercado Pago refuses', async () => { const body = await sentBody({ backUrl: 'http://localhost:6173/student/payments', notificationUrl: 'http://localhost:4000/api/v1/payments/webhooks/mp/pay-1', }); expect(body).not.toHaveProperty('auto_return'); expect(body).not.toHaveProperty('notification_url'); }); }); describe('searchMpPaymentByExternalReference', () => { const realFetch = globalThis.fetch; afterEach(() => { globalThis.fetch = realFetch; }); it('prefers the approved attempt over an earlier rejected one', async () => { globalThis.fetch = (async () => new Response( JSON.stringify({ results: [ { id: 1, status: 'rejected', external_reference: 'pay-1' }, { id: 2, status: 'approved', external_reference: 'pay-1', date_approved: '2026-11-11T03:00:00.000Z' }, ], }), { status: 200 }, )) as unknown as typeof fetch; const found = await searchMpPaymentByExternalReference('token', 'pay-1'); expect(found).toMatchObject({ id: '2', status: 'approved' }); }); });