import assert from 'node:assert/strict'; import test from 'node:test'; import { loadFrontendModule } from './helpers/frontendModule.js'; async function harness(respond) { const calls = [], authErrors = []; const api = await loadFrontendModule( new URL('../../src/helpers/websiteApi.js', import.meta.url), { './api': { API: Object.fromEntries( ['get', 'post'].map((method) => [ method, async (...args) => { calls.push({ method, args }); return respond(); }, ]), ), }, './utils': { showError: (error) => authErrors.push(error) }, }, ); return { ...api, calls, authErrors }; } test('requires strict business success including when HTTP succeeds', async () => { for (const data of [ null, {}, { success: false, message: '权限不足' }, { success: 'true' }, ]) { const api = await harness(() => ({ data })); await assert.rejects( api.requestWebsite('get', '/api/website/page-config'), /权限不足|请求失败/, ); } const api = await harness(() => ({ data: { success: true, data: null } })); assert.equal( await api.requestWebsite('get', '/api/website/page-config'), null, ); }); test('uses the authenticated shared API instance and leaves multipart Content-Type unset', async () => { const api = await harness(() => ({ data: { success: true, data: { url: 'https://cdn.example.com/qr.png' } }, })); const form = new FormData(); await api.requestWebsite('post', '/api/customer-service/upload', form); assert.equal(api.calls[0].args[1], form); assert.equal(api.calls[0].args[2].headers, undefined); assert.equal(api.calls[0].args[2].skipErrorHandler, true); assert.equal(api.calls[0].args[2].timeout, 20000); }); test('handles unauthenticated, rate-limited, non-JSON gateway and network failures', async () => { for (const [response, pattern] of [ [{ status: 401 }, /重新登录/], [{ status: 429, data: 'Too many requests' }, /过于频繁/], [{ status: 502 }, /读取失败/], [{ status: 400, data: { message: '后端业务错误' } }, /后端业务错误/], [undefined, /读取失败/], ]) { const error = Object.assign(new Error('Axios error'), { response }); const api = await harness(() => { throw error; }); await assert.rejects( api.requestWebsite( 'get', '/api/website/page-config', undefined, '读取失败', ), pattern, ); assert.equal(api.authErrors.length, response?.status === 401 ? 1 : 0); } });