/** * 极简测试框架(零依赖,兼容 Node 18+) * 提供 describe / it / expect 与断言方法,并汇总测试报告。 */ let suites = [] let current = null export function describe(name, fn) { current = { name, cases: [] } suites.push(current) fn() current = null } export function it(name, fn) { if (!current) throw new Error('it() 必须写在 describe() 内') current.cases.push({ name, fn }) } export function expect(actual) { return { toBe(expected) { assert(Object.is(actual, expected), `期望 ${fmt(expected)},实际 ${fmt(actual)}`) }, toEqual(expected) { const a = JSON.stringify(actual) const b = JSON.stringify(expected) assert(a === b, `期望 ${b},实际 ${a}`) }, toBeTruthy() { assert(!!actual, `期望为真值,实际 ${fmt(actual)}`) }, toBeFalsy() { assert(!actual, `期望为假值,实际 ${fmt(actual)}`) }, toBeDefined() { assert(actual !== undefined && actual !== null, `期望有值,实际 ${fmt(actual)}`) }, toBeGreaterThan(n) { assert(typeof actual === 'number' && actual > n, `期望 > ${n},实际 ${fmt(actual)}`) }, toBeLessThanOrEqual(n) { assert(typeof actual === 'number' && actual <= n, `期望 <= ${n},实际 ${fmt(actual)}`) }, toContain(s) { assert(String(actual).includes(s), `期望包含 "${s}",实际 ${fmt(actual)}`) }, toHaveLength(n) { assert(actual && actual.length === n, `期望长度 ${n},实际 ${actual && actual.length}`) }, toBeArray() { assert(Array.isArray(actual), `期望为数组,实际 ${fmt(actual)}`) }, toMatch(re) { assert(re.test(String(actual)), `期望匹配 ${re},实际 ${fmt(actual)}`) }, } } /** 断言异步调用必须抛错(用于校验业务规则拦截) */ export async function expectReject(fn, msgPart) { try { await fn() } catch (e) { if (msgPart) { assert(String(e.message).includes(msgPart), `期望错误信息包含 "${msgPart}",实际 "${e.message}"`) } return e } throw new Error('期望抛出异常,但调用成功返回') } function assert(cond, message) { if (!cond) throw new Error(message) } function fmt(v) { if (typeof v === 'string') return `"${v}"` try { return typeof v === 'object' ? JSON.stringify(v) : String(v) } catch (e) { return String(v) } } /** 执行全部用例并输出报告 */ export async function run() { let passed = 0 let failed = 0 const failures = [] console.log('\n=========== 全链路接口测试报告 ===========\n') for (const suite of suites) { console.log(`📦 ${suite.name}`) for (const c of suite.cases) { try { await c.fn() passed++ console.log(` ✅ ${c.name}`) } catch (e) { failed++ failures.push({ suite: suite.name, name: c.name, error: e.message }) console.log(` ❌ ${c.name}\n → ${e.message}`) } } console.log('') } console.log('------------------------------------------') console.log(`用例总数: ${passed + failed} 通过: ${passed} 失败: ${failed}`) console.log('------------------------------------------\n') if (failures.length) { console.log('失败明细:') failures.forEach((f, i) => console.log(` ${i + 1}. [${f.suite}] ${f.name} → ${f.error}`)) console.log('') process.exitCode = 1 } else { console.log('🎉 全部用例通过,前后端接口契约与业务规则校验一致。\n') } // 重置,便于同一进程重复运行 suites = [] return { passed, failed } }