feat(uniapp): 小程序端(用户端 uni-app)源码入库到 uniapp/ 目录
需求:小程序端代码要同时同步到服务器与 git 远程仓库,此前前端仅存在于本地目录(无 remote,从未推送), 服务器与 gitcode 上只有后端。现并入本仓库,复用现有「push 即部署」链路,一次推送双端落地。 - 新增 uniapp/:小程序端源码全量快照(150 文件 / 1.2M) pages(13 页面) · components(fc-navbar/fc-tabbar/fc-post-card/fc-empty) · common(api·utils·mock·assets·store·config) · static(74 图标 + 3 轮播插画 + LOGO) · docs(01-04 交付文档) · tests(零依赖全链路用例) · tools(图标/主题/轮播配图生成脚本) - 明确排除:AGENTS.md(含后台密码、服务器 root 密码、小程序 AppSecret,切勿入库)、 unpackage/(构建产物,由 uniapp/.gitignore 忽略)、node_modules、.DS_Store、*.log - .gitignore 新增 /uniapp/AGENTS.md 兜底(与根 /AGENTS.md、/fluniapp/ 同一约定) - README.md 增补「本项目结构 + 部署链路」章节,说明 uniapp/ 为源码快照、 小程序真正上线仍需微信开发者工具 cli upload 说明:本次为源码快照,未携带前端本地仓库历史——其历史提交中含 AGENTS.md 凭据, 若做 subtree 合并会把密码永久写入本仓库历史,故采用快照方式。
这个提交包含在:
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* 接口契约测试(后台管理端 PC)
|
||||
* 覆盖 10 大模块:数据总览 / 商家 / 会员 / 信息审核 / 评价 / 分销 / 订单 / 财务 / 权限 / 系统设置
|
||||
*/
|
||||
import { describe, it, expect, expectReject } from './harness.mjs'
|
||||
import adminApi from '../common/api/admin.js'
|
||||
|
||||
describe('后台 · 数据总览', () => {
|
||||
it('核心数据看板字段完整', async () => {
|
||||
const o = await adminApi.dashboardOverview()
|
||||
expect(o.pv).toBeGreaterThan(0)
|
||||
expect(o.todayOrderAmount).toBeDefined()
|
||||
expect(o.pendingAudit).toBeDefined()
|
||||
expect(o.memberCount).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('趋势分析支持流量 / 营收 / 用户增长', async () => {
|
||||
const traffic = await adminApi.dashboardTrend('traffic')
|
||||
expect(traffic[0].pv).toBeDefined()
|
||||
const revenue = await adminApi.dashboardTrend('revenue')
|
||||
expect(revenue[0].amount).toBeDefined()
|
||||
const growth = await adminApi.dashboardTrend('userGrowth')
|
||||
expect(growth[0].newUser).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台 · 商家管理', () => {
|
||||
it('商家列表支持状态筛选与关键词检索', async () => {
|
||||
const all = await adminApi.merchants({ page: 1, size: 20 })
|
||||
expect(all.total).toBeGreaterThan(0)
|
||||
const pending = await adminApi.merchants({ status: 0 })
|
||||
expect(pending.list.every((m) => m.auditStatus === 0)).toBe(true)
|
||||
const kw = await adminApi.merchants({ keyword: '物流' })
|
||||
expect(kw.list[0].name).toContain('物流')
|
||||
})
|
||||
|
||||
it('资质审核支持通过 / 驳回,非法状态被拦截', async () => {
|
||||
expect((await adminApi.auditMerchant(2005, 1)).auditStatus).toBe(1)
|
||||
expect((await adminApi.auditMerchant(2005, 2)).auditStatus).toBe(2)
|
||||
await expectReject(() => adminApi.auditMerchant(2005, 9), '审核状态仅支持')
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台 · 会员管理', () => {
|
||||
it('用户列表区分个人 / 商家', async () => {
|
||||
const res = await adminApi.users({ page: 1, size: 20 })
|
||||
const types = new Set(res.list.map((u) => u.userType))
|
||||
expect(types.has(1)).toBe(true)
|
||||
expect(types.has(2)).toBe(true)
|
||||
})
|
||||
|
||||
it('会员权益设置:免费查看条数不能为负', async () => {
|
||||
const r = await adminApi.saveMemberBenefit({ freeView: 30, postDiscount: '7 折' })
|
||||
expect(r.freeView).toBe(30)
|
||||
await expectReject(() => adminApi.saveMemberBenefit({ freeView: -1 }), '不能为负')
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台 · 信息审核', () => {
|
||||
it('待审核列表仅返回 auditStatus=0', async () => {
|
||||
const res = await adminApi.pendingPosts({ page: 1, size: 20 })
|
||||
expect(res.list.every((p) => p.auditStatus === 0)).toBe(true)
|
||||
})
|
||||
|
||||
it('审核通过 / 驳回,非法状态被拦截', async () => {
|
||||
expect((await adminApi.auditPost(104, 1)).auditStatus).toBe(1)
|
||||
expect((await adminApi.auditPost(104, 2)).auditStatus).toBe(2)
|
||||
await expectReject(() => adminApi.auditPost(104, 0), '仅支持通过')
|
||||
})
|
||||
|
||||
it('违规信息可强制下架', async () => {
|
||||
const r = await adminApi.offlinePost(106)
|
||||
expect(r.offline).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台 · 评价管理', () => {
|
||||
it('全平台评价可查看', async () => {
|
||||
const res = await adminApi.comments({ page: 1, size: 20 })
|
||||
expect(res.list.length).toBeGreaterThan(0)
|
||||
expect(res.list[0].score).toBeDefined()
|
||||
})
|
||||
|
||||
it('回复评价需填写内容', async () => {
|
||||
const r = await adminApi.replyComment(5001, '感谢您的评价')
|
||||
expect(r.reply).toBe('感谢您的评价')
|
||||
await expectReject(() => adminApi.replyComment(5001, ''), '回复内容不能为空')
|
||||
})
|
||||
|
||||
it('举报处理列表可读取', async () => {
|
||||
const list = await adminApi.reports()
|
||||
expect(list).toBeArray()
|
||||
expect(list[0].reason).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台 · 分销管理', () => {
|
||||
it('分润设置:可开关、层级、比例', async () => {
|
||||
const s = await adminApi.distSetting()
|
||||
expect(s.enabled).toBe(true)
|
||||
expect(s.level).toBe(2)
|
||||
})
|
||||
|
||||
it('分佣比例一级+二级不得超过 100%', async () => {
|
||||
const ok = await adminApi.saveDistSetting({ level1Rate: 20, level2Rate: 10 })
|
||||
expect(ok.level1Rate).toBe(20)
|
||||
await expectReject(
|
||||
() => adminApi.saveDistSetting({ level1Rate: 80, level2Rate: 40 }),
|
||||
'不能超过 100%'
|
||||
)
|
||||
})
|
||||
|
||||
it('提现审核:打款 / 驳回(驳回需原因)', async () => {
|
||||
expect((await adminApi.handleWithdraw(2, 'pay')).status).toBe('paid')
|
||||
await expectReject(() => adminApi.handleWithdraw(3, 'reject'), '需填写原因')
|
||||
expect((await adminApi.handleWithdraw(3, 'reject', '账户异常')).status).toBe('rejected')
|
||||
})
|
||||
|
||||
it('提现列表可读取', async () => {
|
||||
const list = await adminApi.withdraws()
|
||||
expect(list).toBeArray()
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台 · 订单管理', () => {
|
||||
it('订单列表按类型筛选(发布单条付费记录)', async () => {
|
||||
const all = await adminApi.orders({ page: 1, size: 50 })
|
||||
expect(all.total).toBeGreaterThan(0)
|
||||
const posts = await adminApi.orders({ type: 'post' })
|
||||
expect(posts.list.every((o) => o.type === 'post')).toBe(true)
|
||||
})
|
||||
|
||||
it('退款金额必须大于 0', async () => {
|
||||
expect((await adminApi.refund(3001, 5, '用户申请')).refunded).toBe(true)
|
||||
await expectReject(() => adminApi.refund(3001, 0), '退款金额需大于 0')
|
||||
})
|
||||
|
||||
it('支持补单', async () => {
|
||||
const r = await adminApi.supplement('PO20240101001')
|
||||
expect(r.supplemented).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台 · 财务管理', () => {
|
||||
it('资金流水支持按类型筛选', async () => {
|
||||
const all = await adminApi.financeFlows({ page: 1, size: 50 })
|
||||
expect(all.total).toBeGreaterThan(0)
|
||||
const income = await adminApi.financeFlows({ type: 'income' })
|
||||
expect(income.list.every((f) => f.type === 'income')).toBe(true)
|
||||
})
|
||||
|
||||
it('财务报表支持日/月/年导出数据结构', async () => {
|
||||
const day = await adminApi.financeReport('day')
|
||||
expect(day.period).toBe('day')
|
||||
expect(day.rows[0].net).toBeDefined()
|
||||
const month = await adminApi.financeReport('month')
|
||||
expect(month.period).toBe('month')
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台 · 权限管理', () => {
|
||||
it('角色管理:内置超级管理员/运营/客服/财务', async () => {
|
||||
const roles = await adminApi.roles()
|
||||
const names = roles.map((r) => r.name)
|
||||
expect(names).toContain('超级管理员')
|
||||
expect(names).toContain('运营')
|
||||
})
|
||||
|
||||
it('新建角色必须有名称与权限', async () => {
|
||||
const r = await adminApi.saveRole({ name: '审核员', permissions: ['post'] })
|
||||
expect(r.id).toBeDefined()
|
||||
await expectReject(() => adminApi.saveRole({ permissions: ['post'] }), '角色名称不能为空')
|
||||
await expectReject(() => adminApi.saveRole({ name: 'x' }), '请至少分配一项权限')
|
||||
})
|
||||
|
||||
it('子账号与操作日志可查询', async () => {
|
||||
const accs = await adminApi.accounts()
|
||||
expect(accs[0].roleName).toBeDefined()
|
||||
const logs = await adminApi.logs({ page: 1, size: 20 })
|
||||
expect(logs.list[0].action).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台 · 系统设置', () => {
|
||||
it('基础配置:小程序名称必填', async () => {
|
||||
const b = await adminApi.baseSetting()
|
||||
expect(b.appName).toBeDefined()
|
||||
const r = await adminApi.saveBaseSetting({ appName: '同城分类信息' })
|
||||
expect(r.appName).toBe('同城分类信息')
|
||||
await expectReject(() => adminApi.saveBaseSetting({}), '小程序名称不能为空')
|
||||
})
|
||||
|
||||
it('支付配置:商户号与密钥必填', async () => {
|
||||
const r = await adminApi.savePaySetting({ mchId: '1900000001', apiKey: 'k' })
|
||||
expect(r.configured).toBe(true)
|
||||
await expectReject(() => adminApi.savePaySetting({ apiKey: 'k' }), '商户号不能为空')
|
||||
await expectReject(() => adminApi.savePaySetting({ mchId: '1' }), '支付密钥不能为空')
|
||||
})
|
||||
|
||||
it('费用标准:单条发布价与会员套餐价动态设置', async () => {
|
||||
const fee = await adminApi.feeSetting()
|
||||
expect(fee.singlePost).toBeDefined()
|
||||
expect(fee.memberYear).toBeDefined()
|
||||
const r = await adminApi.saveFeeSetting({ singlePost: 6, memberMonth: 25 })
|
||||
expect(r.singlePost).toBe(6)
|
||||
await expectReject(() => adminApi.saveFeeSetting({ singlePost: -1 }), '不能为负')
|
||||
})
|
||||
|
||||
it('地区管理:同城服务区域划分', async () => {
|
||||
const areas = await adminApi.areas()
|
||||
expect(areas.length).toBeGreaterThan(0)
|
||||
const r = await adminApi.saveArea({ name: '乌当区', sort: 6 })
|
||||
expect(r.id).toBeDefined()
|
||||
await expectReject(() => adminApi.saveArea({}), '区域名称不能为空')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
/**
|
||||
* 接口契约测试(用户端)
|
||||
* 目的:验证「前端 api 模块 ↔ 后端响应结构」字段级契约一致。
|
||||
*/
|
||||
import { describe, it, expect, expectReject } from './harness.mjs'
|
||||
import { authApi, homeApi, postApi, memberApi, distributionApi, messageApi } from '../common/api/index.js'
|
||||
|
||||
describe('用户端 · 认证与登录', () => {
|
||||
it('微信手机号快捷获取返回真实号码;缺 code 时报错(v1.0.8)', async () => {
|
||||
const res = await authApi.wxPhone({ code: 'wx_phone_code_001' })
|
||||
expect(res.phone).toMatch(/^1\d{10}$/)
|
||||
await expectReject(() => authApi.wxPhone({}), '缺少手机号授权 code')
|
||||
})
|
||||
|
||||
it('手机号绑定:格式校验 + 落库回显', async () => {
|
||||
await expectReject(() => authApi.bindPhone({ phone: '1380000' }), '手机号格式不正确')
|
||||
const res = await authApi.bindPhone({ phone: '13800001111' })
|
||||
expect(res.phone).toBe('13800001111')
|
||||
})
|
||||
|
||||
it('微信昵称/头像可随登录带上并回显(v1.0.9)', async () => {
|
||||
const res = await authApi.wxLogin({ code: 'wx_code_profile', nickname: '微信小明', avatar: '/uploads/mock/avatar.png' })
|
||||
expect(res.userInfo.nickname).toBe('微信小明')
|
||||
expect(res.userInfo.avatar).toContain('/uploads/')
|
||||
})
|
||||
|
||||
it('头像上传返回可持久化路径与完整地址', async () => {
|
||||
const up = await authApi.uploadAvatar('/tmp/avatar.png')
|
||||
expect(up.avatar).toContain('/uploads/')
|
||||
expect(up.url).toContain('http')
|
||||
await expectReject(() => authApi.uploadAvatar(''), '未接收到上传文件')
|
||||
})
|
||||
|
||||
it('资料更新:可补填昵称/头像,空提交被拦截', async () => {
|
||||
const info = await authApi.saveProfile({ nickname: '昵称补充' })
|
||||
expect(info.nickname).toBe('昵称补充')
|
||||
await expectReject(() => authApi.saveProfile({}), '没有需要更新的资料')
|
||||
})
|
||||
|
||||
it('微信登录返回 token 与用户信息', async () => {
|
||||
const res = await authApi.wxLogin({ code: 'wx_code_001' })
|
||||
expect(res.token).toContain('mock_token')
|
||||
expect(res.userInfo.nickname).toBeDefined()
|
||||
})
|
||||
|
||||
it('手机号绑定校验格式', async () => {
|
||||
const ok = await authApi.bindPhone({ phone: '13800001111' })
|
||||
expect(ok.phone).toBe('13800001111')
|
||||
await expectReject(() => authApi.bindPhone({ phone: '123' }), '手机号格式不正确')
|
||||
})
|
||||
|
||||
it('用户类型切换:商家必须带资质', async () => {
|
||||
const res = await authApi.switchType({ userType: 1 })
|
||||
expect(res.userType).toBe(1)
|
||||
expect(res.needAudit).toBe(false)
|
||||
const biz = await authApi.switchType({ userType: 2, license: '营业执照.jpg' })
|
||||
expect(biz.needAudit).toBe(true)
|
||||
await expectReject(() => authApi.switchType({ userType: 2 }), '需上传营业执照')
|
||||
await expectReject(() => authApi.switchType({ userType: 9 }), '用户类型不合法')
|
||||
})
|
||||
|
||||
it('获取用户资料', async () => {
|
||||
const res = await authApi.profile()
|
||||
expect(res.phone).toBeDefined()
|
||||
expect(res.userType).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('用户端 · 首页与展示', () => {
|
||||
it('轮播广告位返回颜色与跳转链接', async () => {
|
||||
const list = await homeApi.banners()
|
||||
expect(list).toBeArray()
|
||||
expect(list[0].link).toContain('/pages/')
|
||||
})
|
||||
|
||||
it('分类导航返回 8 个一级分类', async () => {
|
||||
const list = await homeApi.categories()
|
||||
expect(list.length).toBe(8)
|
||||
expect(list[0].iconKey).toBeDefined()
|
||||
expect(list[0].name).toBeTruthy()
|
||||
})
|
||||
|
||||
it('信息流支持分类 / 区域 / 排序 / 分页', async () => {
|
||||
const byCat = await homeApi.feed({ categoryId: 3, page: 1, size: 10 })
|
||||
expect(byCat.list.every((p) => p.categoryId === 3)).toBe(true)
|
||||
const byArea = await homeApi.feed({ area: '云岩区' })
|
||||
expect(byArea.list.every((p) => p.area === '云岩区')).toBe(true)
|
||||
// 排序口径 v1.0.7:后台置顶的信息始终排在最前,其余按所选排序
|
||||
const hot = await homeApi.feed({ sort: 'hot' })
|
||||
const hotRest = hot.list.filter((p) => !p.isTop)
|
||||
for (let i = 1; i < hotRest.length; i++) {
|
||||
expect(hotRest[i - 1].views).toBeGreaterThan(hotRest[i].views - 1)
|
||||
}
|
||||
if (hot.list.some((p) => p.isTop)) {
|
||||
expect(hot.list[0].isTop).toBe(true)
|
||||
}
|
||||
const page1 = await homeApi.feed({ page: 1, size: 2 })
|
||||
expect(page1.list).toHaveLength(2)
|
||||
expect(page1.hasMore).toBe(true)
|
||||
expect(page1.total).toBeGreaterThan(2)
|
||||
})
|
||||
|
||||
it('置顶信息在信息流中排首位(后台手动置顶)', async () => {
|
||||
const res = await homeApi.feed({ page: 1, size: 10 })
|
||||
const pinned = res.list.filter((p) => p.isTop)
|
||||
expect(pinned.length).toBeGreaterThan(0)
|
||||
// 所有置顶项都排在非置顶项之前
|
||||
const firstUnpinned = res.list.findIndex((p) => !p.isTop)
|
||||
const lastPinned = res.list.map((p) => !!p.isTop).lastIndexOf(true)
|
||||
expect(lastPinned).toBeLessThanOrEqual(firstUnpinned - 1)
|
||||
expect(res.list[0].isTop).toBe(true)
|
||||
})
|
||||
|
||||
it('关键词搜索命中标题', async () => {
|
||||
const res = await homeApi.feed({ keyword: '快递' })
|
||||
expect(res.total).toBeGreaterThan(0)
|
||||
expect(res.list[0].title).toContain('快递')
|
||||
})
|
||||
|
||||
it('热门搜索词可用', async () => {
|
||||
const list = await homeApi.hotKeywords()
|
||||
expect(list.length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('用户端 · 信息发布与详情', () => {
|
||||
it('免费发布返回待审核状态且无订单', async () => {
|
||||
const res = await postApi.create({ title: '测试标题', content: '内容', paid: false })
|
||||
expect(res.postId).toBeDefined()
|
||||
expect(res.auditStatus).toBe(0)
|
||||
expect(res.order).toBeFalsy()
|
||||
})
|
||||
|
||||
it('付费发布返回支付订单', async () => {
|
||||
const res = await postApi.create({ title: '付费标题', content: '内容', paid: true, amount: 5, payType: 'wxpay' })
|
||||
expect(res.order.orderNo).toContain('PO')
|
||||
expect(res.order.amount).toBe(5)
|
||||
})
|
||||
|
||||
it('必填校验:标题 / 内容', async () => {
|
||||
await expectReject(() => postApi.create({ content: 'x' }), '标题不能为空')
|
||||
await expectReject(() => postApi.create({ title: 'x' }), '内容不能为空')
|
||||
})
|
||||
|
||||
it('草稿箱保存与读取', async () => {
|
||||
const d = await postApi.saveDraft({ title: '草稿A', content: 'bbb' })
|
||||
expect(d.draftId).toBeDefined()
|
||||
const list = await postApi.drafts()
|
||||
expect(list).toBeArray()
|
||||
})
|
||||
|
||||
it('详情返回发布者与互动数据', async () => {
|
||||
const res = await postApi.detail(102)
|
||||
expect(res.id).toBe(102)
|
||||
expect(res.publisher.name).toBeDefined()
|
||||
expect(res.views).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('付费查看:支持微信 / 余额,非法方式被拦截', async () => {
|
||||
const wx = await postApi.payView(101, { payType: 'wxpay' })
|
||||
expect(wx.unlocked).toBe(true)
|
||||
expect(wx.contact.phone).toBeDefined()
|
||||
const bal = await postApi.payView(101, { payType: 'balance' })
|
||||
expect(bal.unlocked).toBe(true)
|
||||
await expectReject(() => postApi.payView(101, { payType: 'alipay' }), '支付方式不支持')
|
||||
})
|
||||
|
||||
it('评价互动:评分 1-5 校验', async () => {
|
||||
const ok = await postApi.comment(101, { score: 5, content: '很好' })
|
||||
expect(ok.commentId).toBeDefined()
|
||||
await expectReject(() => postApi.comment(101, { score: 9, content: 'x' }), '评分需在 1-5 之间')
|
||||
await expectReject(() => postApi.comment(101, { score: 5 }), '评价内容不能为空')
|
||||
})
|
||||
})
|
||||
|
||||
describe('用户端 · 会员中心', () => {
|
||||
it('会员套餐:月/季/年三档', async () => {
|
||||
const plans = await memberApi.plans()
|
||||
expect(plans).toHaveLength(3)
|
||||
expect(plans[0].name).toBe('月卡')
|
||||
expect(plans[2].name).toBe('年卡')
|
||||
})
|
||||
|
||||
it('会员权益可读取', async () => {
|
||||
const b = await memberApi.benefits()
|
||||
expect(b.freeView).toBeGreaterThan(0)
|
||||
expect(b.benefits.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('开通会员:套餐必选、支付方式受控', async () => {
|
||||
const res = await memberApi.open({ planId: 'M12', payType: 'wxpay' })
|
||||
expect(res.status).toBe('paid')
|
||||
expect(res.orderNo).toContain('MO')
|
||||
await expectReject(() => memberApi.open({ payType: 'wxpay' }), '请选择会员套餐')
|
||||
await expectReject(() => memberApi.open({ planId: 'M1', payType: 'card' }), '支付方式不支持')
|
||||
})
|
||||
|
||||
it('订单管理包含发布 / 会员 / 充值三类', async () => {
|
||||
const res = await memberApi.orders({ page: 1, size: 50 })
|
||||
const types = res.list.map((o) => o.type)
|
||||
expect(types).toContain('post')
|
||||
expect(types).toContain('member')
|
||||
expect(types).toContain('recharge')
|
||||
})
|
||||
|
||||
it('我的资产包含余额 / 优惠券 / 积分', async () => {
|
||||
const a = await memberApi.assets()
|
||||
expect(a.balance).toBeDefined()
|
||||
expect(a.coupons).toBeArray()
|
||||
expect(a.points).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('用户端 · 分销中心', () => {
|
||||
it('佣金概览字段完整', async () => {
|
||||
const o = await distributionApi.overview()
|
||||
expect(o.withdrawable).toBeDefined()
|
||||
expect(o.totalCommission).toBeDefined()
|
||||
expect(o.inviteCode).toBeDefined()
|
||||
})
|
||||
|
||||
it('团队管理按一级/二级筛选', async () => {
|
||||
const all = await distributionApi.team({ page: 1, size: 50 })
|
||||
expect(all.list.length).toBeGreaterThan(0)
|
||||
const l1 = await distributionApi.team({ level: 1 })
|
||||
expect(l1.list.every((t) => t.level === 1)).toBe(true)
|
||||
const l2 = await distributionApi.team({ level: 2 })
|
||||
expect(l2.list.every((t) => t.level === 2)).toBe(true)
|
||||
})
|
||||
|
||||
it('提现校验:金额合法且不超过可提现余额', async () => {
|
||||
const res = await distributionApi.withdraw({ amount: 10, channel: 'wxpay' })
|
||||
expect(res.status).toBe('auditing')
|
||||
await expectReject(() => distributionApi.withdraw({ amount: 0 }), '提现金额不合法')
|
||||
await expectReject(() => distributionApi.withdraw({ amount: 999999 }), '超过可提现余额')
|
||||
})
|
||||
|
||||
it('提现记录可查询', async () => {
|
||||
const list = await distributionApi.withdrawRecords()
|
||||
expect(list).toBeArray()
|
||||
})
|
||||
})
|
||||
|
||||
describe('用户端 · 消息中心', () => {
|
||||
it('系统通知与互动消息分类正确', async () => {
|
||||
const sys = await messageApi.list({ type: 'system' })
|
||||
expect(sys.list.every((m) => m.type === 'system')).toBe(true)
|
||||
const inter = await messageApi.list({ type: 'interact' })
|
||||
expect(inter.list.every((m) => m.type === 'interact')).toBe(true)
|
||||
})
|
||||
|
||||
it('标记已读', async () => {
|
||||
const res = await messageApi.read(1)
|
||||
expect(res.read).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
207
uniapp/tests/banners.test.mjs
普通文件
207
uniapp/tests/banners.test.mjs
普通文件
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* 首页轮播配图(Banner v2 · 绿底 + 白色插画)测试
|
||||
* 覆盖:
|
||||
* 1) static/banners 白色插画资源完整性(PNG 魔数 / 192×192 / 真实透明 / 体积)
|
||||
* 2) common/assets/banners.js 的取图、金色点缀与底色回落规则
|
||||
* 3) common/mock/data.js 轮播数据与「绿=平台、金=价值」主题规则一致
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import url from 'node:url'
|
||||
import { describe, it, expect } from './harness.mjs'
|
||||
import {
|
||||
BANNER_BASE,
|
||||
BANNER_ART,
|
||||
BANNER_BG,
|
||||
bannerArtUrl,
|
||||
bannerHasValue,
|
||||
bannerBg,
|
||||
} from '../common/assets/banners.js'
|
||||
import { datasets } from '../common/mock/data.js'
|
||||
import { decodePng, transparentRatio } from '../tools/png-util.mjs'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '..')
|
||||
const ART_DIR = path.join(ROOT, 'static', 'banners')
|
||||
|
||||
describe('轮播配图 · 资源完整性', () => {
|
||||
it('内置插画共 3 套,注册表与文件一一对应', () => {
|
||||
expect(BANNER_ART.length).toBe(3)
|
||||
const missing = BANNER_ART.filter((f) => !fs.existsSync(path.join(ART_DIR, f)))
|
||||
expect(missing).toEqual([])
|
||||
expect(BANNER_BASE).toBe('/static/banners/')
|
||||
})
|
||||
|
||||
it('每张插画都是有效 PNG 且体积可控(单张 < 8KB)', () => {
|
||||
for (const f of BANNER_ART) {
|
||||
const buf = fs.readFileSync(path.join(ART_DIR, f))
|
||||
expect(buf.slice(0, 8).toString('hex')).toBe('89504e470d0a1a0a')
|
||||
expect(buf.length).toBeLessThanOrEqual(8 * 1024)
|
||||
}
|
||||
const total = BANNER_ART.reduce((s, f) => s + fs.statSync(path.join(ART_DIR, f)).size, 0)
|
||||
expect(total).toBeLessThanOrEqual(24 * 1024) // 3 张总计不超过 24KB,不给主包添负担
|
||||
})
|
||||
|
||||
it('每张插画都是 192×192 且具备真实透明通道', () => {
|
||||
for (const f of BANNER_ART) {
|
||||
const img = decodePng(fs.readFileSync(path.join(ART_DIR, f)))
|
||||
expect(img.width).toBe(192)
|
||||
expect(img.height).toBe(192)
|
||||
expect(img.rgba[3]).toBe(0) // 左上角必须完全透明
|
||||
expect(transparentRatio(img) >= 0.1).toBeTruthy()
|
||||
}
|
||||
})
|
||||
|
||||
it('插画图形为白色/薄荷系(暗像素占比极低,说明压在绿底上够亮)', () => {
|
||||
for (const f of BANNER_ART) {
|
||||
const img = decodePng(fs.readFileSync(path.join(ART_DIR, f)))
|
||||
let dark = 0
|
||||
let visible = 0
|
||||
for (let i = 0; i < img.rgba.length; i += 4) {
|
||||
if (img.rgba[i + 3] < 32) continue
|
||||
visible++
|
||||
const lum = (img.rgba[i] * 299 + img.rgba[i + 1] * 587 + img.rgba[i + 2] * 114) / 1000
|
||||
if (lum < 150) dark++
|
||||
}
|
||||
expect(visible).toBeGreaterThan(0)
|
||||
expect(dark / visible < 0.02).toBeTruthy()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('轮播配图 · 取图与主题规则', () => {
|
||||
it('按位置循环取插画(第 4 条回到第 1 套)', () => {
|
||||
expect(bannerArtUrl(0)).toBe('/static/banners/banner-art-1.png')
|
||||
expect(bannerArtUrl(1)).toBe('/static/banners/banner-art-2.png')
|
||||
expect(bannerArtUrl(2)).toBe('/static/banners/banner-art-3.png')
|
||||
expect(bannerArtUrl(3)).toBe('/static/banners/banner-art-1.png')
|
||||
})
|
||||
|
||||
it('金色价值点缀只给「直降 / 免费」两条(第 3 条为平台服务,不带金色)', () => {
|
||||
expect(bannerHasValue(0)).toBe(true)
|
||||
expect(bannerHasValue(1)).toBe(true)
|
||||
expect(bannerHasValue(2)).toBe(false)
|
||||
expect(bannerHasValue(3)).toBe(true)
|
||||
})
|
||||
|
||||
it('后台下发渐变时原样生效', () => {
|
||||
const custom = 'linear-gradient(90deg, #04302a 0%, #0e7c66 100%)'
|
||||
expect(bannerBg({ color: custom }, 0)).toBe(custom)
|
||||
})
|
||||
|
||||
it('后台想「纯色」时用同色双色标渐变表达,同样原样生效', () => {
|
||||
const solid = 'linear-gradient(135deg, #0E7C66 0%, #0E7C66 100%)'
|
||||
expect(bannerBg({ color: solid }, 0)).toBe(solid)
|
||||
})
|
||||
|
||||
it('rgba 色标的渐变也被接受(不局限于 hex)', () => {
|
||||
const rgba = 'linear-gradient(135deg, rgba(24,165,135,.9) 0%, #0a5d4d 100%)'
|
||||
expect(bannerBg({ color: rgba }, 0)).toBe(rgba)
|
||||
})
|
||||
|
||||
it('旧暖色纯色 / 空底色 / 被截断的半截值一律回落到内置生态绿渐变(主题护栏)', () => {
|
||||
expect(bannerBg({ color: '#FF8A5B' }, 0)).toBe(BANNER_BG[0])
|
||||
expect(bannerBg({ color: '#FFB86B' }, 1)).toBe(BANNER_BG[1])
|
||||
expect(bannerBg({}, 2)).toBe(BANNER_BG[2])
|
||||
expect(bannerBg(null, 3)).toBe(BANNER_BG[0])
|
||||
expect(bannerBg({ color: '' }, 4)).toBe(BANNER_BG[1])
|
||||
// 旧库 color 列只有 varchar(16),渐变会被截断成半截值(渲染成非法样式 → 卡片空白),必须拦下
|
||||
expect(bannerBg({ color: 'linear-gradient(' }, 5)).toBe(BANNER_BG[2])
|
||||
expect(bannerBg({ color: 'linear-gradient(135deg' }, 6)).toBe(BANNER_BG[0])
|
||||
expect(bannerBg({ color: 'linear-gradient(135deg)' }, 7)).toBe(BANNER_BG[1])
|
||||
})
|
||||
|
||||
it('内置底色的 3 条渐变必须是春绿系(105deg 亮绿起点 → 深绿收尾,不含暖色)', () => {
|
||||
expect(BANNER_BG.length).toBe(3)
|
||||
// 起点落在品牌亮绿族(#00e070 / #00c860 / #049e52 / #04874a),收尾必须落到深绿(白字区)
|
||||
const START_OK = /linear-gradient\(105deg, #(00e070|00d96c|00e878|00c860|049e52|04874a) /
|
||||
const END_OK = /#(046b3b|045c34|023a21|03512e) 100%\)$/
|
||||
for (const bg of BANNER_BG) {
|
||||
expect(START_OK.test(bg)).toBeTruthy()
|
||||
expect(END_OK.test(bg)).toBeTruthy()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('轮播配图 · Mock 数据契约', () => {
|
||||
it('轮播 3 条,字段与后端 /home/banners 一致(id/title/image/link/color)', () => {
|
||||
expect(datasets.banners.length).toBe(3)
|
||||
for (const b of datasets.banners) {
|
||||
expect(typeof b.id === 'number').toBeTruthy()
|
||||
expect(b.title.length > 0).toBeTruthy()
|
||||
expect(typeof b.image).toBe('string')
|
||||
expect(b.link.indexOf('/pages/')).toBe(0)
|
||||
expect(b.color.indexOf('gradient(') !== -1).toBeTruthy()
|
||||
}
|
||||
})
|
||||
|
||||
it('每条轮播的底色都能直接生效(不再走回落分支)', () => {
|
||||
datasets.banners.forEach((b, i) => {
|
||||
expect(bannerBg(b, i)).toBe(b.color)
|
||||
expect(b.color.indexOf('linear-gradient(')).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
it('轮播标题与后台种子一致(前端展示与安装脚本同一份文案)', () => {
|
||||
expect(datasets.banners.map((b) => b.title)).toEqual([
|
||||
'同城好物节 · 二手直降',
|
||||
'招聘旺季 · 免费发布',
|
||||
'本地服务 · 上门更省心',
|
||||
])
|
||||
})
|
||||
describe('春绿主题规则 · 亮绿面与白字/墨绿字', () => {
|
||||
const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8')
|
||||
const vueFiles = () => {
|
||||
const out = []
|
||||
const walk = (dir) => {
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
const full = path.join(dir, name)
|
||||
if (fs.statSync(full).isDirectory()) walk(full)
|
||||
else if (name.endsWith('.vue')) out.push(full)
|
||||
}
|
||||
}
|
||||
walk(path.join(ROOT, 'pages'))
|
||||
walk(path.join(ROOT, 'components'))
|
||||
return out
|
||||
}
|
||||
|
||||
it('亮绿面($fc-gradient-primary / $fc-primary)上不得直接配白字(白字压亮绿仅 1.8:1)', () => {
|
||||
const bad = []
|
||||
for (const f of vueFiles()) {
|
||||
const lines = read(path.relative(ROOT, f)).split(/\r?\n/)
|
||||
lines.forEach((line, i) => {
|
||||
if (!/background(-color)?: \$fc-(gradient-primary|primary);/.test(line)) return
|
||||
const next = lines.slice(i + 1, i + 4).join('\n')
|
||||
if (/color: #ffffff;/.test(next)) bad.push(`${path.relative(ROOT, f)}:${i + 1}`)
|
||||
})
|
||||
}
|
||||
expect(bad).toEqual([])
|
||||
})
|
||||
|
||||
it('白字只落在深绿面($fc-gradient-hero)上:hero 仍保留白字', () => {
|
||||
const heroFiles = [
|
||||
['pages/index/index.vue', '.home__header'],
|
||||
['pages/mine/index.vue', '.mine__header'],
|
||||
['pages/member/index.vue', '.vip__header'],
|
||||
['pages/distribution/index.vue', '.dist__header'],
|
||||
]
|
||||
for (const [file, sel] of heroFiles) {
|
||||
const src = read(file)
|
||||
const i = src.indexOf(sel)
|
||||
expect(i > -1).toBeTruthy()
|
||||
expect(src.slice(i, i + 120).indexOf('$fc-gradient-hero') > -1).toBeTruthy()
|
||||
}
|
||||
})
|
||||
|
||||
it('轮播卡文字用墨绿字($fc-primary-ink)+ 提亮罩,白插画留右侧深绿区', () => {
|
||||
const src = read('pages/index/index.vue')
|
||||
const title = src.slice(src.indexOf('.home__banner-title'), src.indexOf('.home__banner-title') + 220)
|
||||
expect(title.indexOf('color: $fc-primary-ink;') > -1).toBeTruthy()
|
||||
const shade = src.slice(src.indexOf('.home__banner-shade'), src.indexOf('.home__banner-shade') + 300)
|
||||
expect(shade.indexOf('rgba(255, 255, 255, 0.22)') > -1).toBeTruthy()
|
||||
expect(shade.indexOf('rgba(4, 48, 42, 0.5)') === -1).toBeTruthy()
|
||||
// 三底色均为「亮绿(左)→ 深绿(右)」的 105deg,白插画落在右侧深绿端
|
||||
for (const bg of BANNER_BG) expect(bg.indexOf('105deg') > -1).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
188
uniapp/tests/e2e.flow.test.mjs
普通文件
188
uniapp/tests/e2e.flow.test.mjs
普通文件
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* 全链路(端到端)业务流测试
|
||||
* 模拟真实用户路径:「浏览 → 登录 → 发布 → 支付 → 审核 → 查看 → 评价 → 会员 → 分销 → 提现 → 消息」
|
||||
* 并联动后台管理端,验证前后端模块串通一致。
|
||||
*/
|
||||
import { describe, it, expect, expectReject } from './harness.mjs'
|
||||
import { authApi, homeApi, postApi, memberApi, distributionApi, messageApi, adminApi } from '../common/api/index.js'
|
||||
|
||||
describe('全链路 E2E · 用户端主路径', () => {
|
||||
it('STEP1 未登录可浏览:首页 → 分类 → 搜索', async () => {
|
||||
const [banners, categories] = await Promise.all([homeApi.banners(), homeApi.categories()])
|
||||
expect(banners.length).toBeGreaterThan(0)
|
||||
expect(categories.length).toBe(8)
|
||||
|
||||
const category = categories[0]
|
||||
const feed = await homeApi.feed({ categoryId: category.id, sort: 'new', page: 1, size: 10 })
|
||||
expect(feed.list.every((p) => p.categoryId === category.id)).toBe(true)
|
||||
|
||||
const search = await homeApi.feed({ keyword: '快递' })
|
||||
expect(search.total).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('STEP2 登录与身份切换(个人 → 商家需资质)', async () => {
|
||||
const login = await authApi.wxLogin({ code: 'wx_code_e2e' })
|
||||
expect(login.token).toBeTruthy()
|
||||
const bind = await authApi.bindPhone({ phone: '13800001111' })
|
||||
expect(bind.phone).toBe('13800001111')
|
||||
await expectReject(() => authApi.switchType({ userType: 2 }), '需上传营业执照')
|
||||
const biz = await authApi.switchType({ userType: 2, license: 'license.jpg' })
|
||||
expect(biz.needAudit).toBe(true)
|
||||
})
|
||||
|
||||
it('STEP3 发布付费信息并生成支付订单', async () => {
|
||||
const created = await postApi.create({
|
||||
categoryId: 3,
|
||||
title: 'E2E 二手笔记本转让',
|
||||
content: '九成新,支持当面验机。',
|
||||
paid: true,
|
||||
amount: 5,
|
||||
payType: 'wxpay',
|
||||
})
|
||||
expect(created.auditStatus).toBe(0) // 待审核
|
||||
expect(created.order.orderNo).toContain('PO')
|
||||
expect(created.order.amount).toBe(5)
|
||||
})
|
||||
|
||||
it('STEP4 草稿箱:自动保存 → 恢复编辑', async () => {
|
||||
const saved = await postApi.saveDraft({ title: '未完成的草稿', content: '???', categoryId: 2 })
|
||||
expect(saved.draftId).toBeDefined()
|
||||
const drafts = await postApi.drafts()
|
||||
expect(drafts.length).toBeGreaterThan(0)
|
||||
expect(drafts[0].savedAt).toBeDefined()
|
||||
})
|
||||
|
||||
it('STEP5 详情 → 付费解锁联系方式 → 评价互动', async () => {
|
||||
const detail = await postApi.detail(102)
|
||||
expect(detail.publisher.name).toBeTruthy()
|
||||
|
||||
await expectReject(() => postApi.payView(102, { payType: 'alipay' }), '支付方式不支持')
|
||||
|
||||
const unlocked = await postApi.payView(102, { payType: 'balance' })
|
||||
expect(unlocked.unlocked).toBe(true)
|
||||
expect(unlocked.contact.phone).toMatch(/^1\d{10}$/)
|
||||
|
||||
const cmt = await postApi.comment(102, { score: 5, content: '信息真实,联系很顺畅' })
|
||||
expect(cmt.commentId).toBeDefined()
|
||||
await expectReject(() => postApi.comment(102, { score: 6, content: 'x' }), '评分需在 1-5 之间')
|
||||
})
|
||||
|
||||
it('STEP6 开通会员 → 订单与资产联动', async () => {
|
||||
const plans = await memberApi.plans()
|
||||
const year = plans.find((p) => p.name === '年卡')
|
||||
const order = await memberApi.open({ planId: year.planId, payType: 'wxpay' })
|
||||
expect(order.status).toBe('paid')
|
||||
|
||||
const orders = await memberApi.orders({ page: 1, size: 50 })
|
||||
expect(orders.total).toBeGreaterThan(0)
|
||||
expect((await memberApi.assets()).balance).toBeDefined()
|
||||
})
|
||||
|
||||
it('STEP7 分销推广 → 团队业绩 → 申请提现', async () => {
|
||||
const overview = await distributionApi.overview()
|
||||
expect(overview.inviteCode).toBeTruthy()
|
||||
|
||||
const team = await distributionApi.team({ page: 1, size: 50 })
|
||||
expect(team.list.filter((t) => t.level === 1).length).toBeGreaterThan(0)
|
||||
|
||||
const wd = await distributionApi.withdraw({ amount: overview.withdrawable, channel: 'wxpay' })
|
||||
expect(wd.status).toBe('auditing')
|
||||
await expectReject(
|
||||
() => distributionApi.withdraw({ amount: overview.withdrawable + 1 }),
|
||||
'超过可提现余额'
|
||||
)
|
||||
})
|
||||
|
||||
it('STEP8 消息中心:接收审核/到期/互动通知', async () => {
|
||||
const sys = await messageApi.list({ type: 'system' })
|
||||
expect(sys.list.length).toBeGreaterThan(0)
|
||||
expect((await messageApi.read(sys.list[0].id)).read).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('全链路 E2E · 后台端管理闭环', () => {
|
||||
it('STEP9 数据总览 → 待审核数量驱动审核队列', async () => {
|
||||
const overview = await adminApi.dashboardOverview()
|
||||
const pending = await adminApi.pendingPosts({ page: 1, size: 50 })
|
||||
expect(pending.total).toBeGreaterThan(0)
|
||||
expect(overview.pendingAudit).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('STEP10 审核用户发布的信息(快速通过)', async () => {
|
||||
const pending = await adminApi.pendingPosts({ page: 1, size: 1 })
|
||||
const target = pending.list[0]
|
||||
expect((await adminApi.auditPost(target.id, 1)).auditStatus).toBe(1)
|
||||
})
|
||||
|
||||
it('STEP11 商家资质审核 + 违规信息强制下架', async () => {
|
||||
await expectReject(() => adminApi.auditMerchant(2005, 3), '审核状态仅支持')
|
||||
expect((await adminApi.auditMerchant(2005, 1)).auditStatus).toBe(1)
|
||||
expect((await adminApi.offlinePost(106)).offline).toBe(true)
|
||||
})
|
||||
|
||||
it('STEP12 评价回复 + 举报处理', async () => {
|
||||
expect((await adminApi.replyComment(5003, '已核实并处理,感谢反馈')).reply).toBeTruthy()
|
||||
const reports = await adminApi.reports()
|
||||
expect(reports.some((r) => r.status === 'pending')).toBe(true)
|
||||
})
|
||||
|
||||
it('STEP13 分销提现审核打款(与 STEP7 联动)', async () => {
|
||||
const list = await adminApi.withdraws()
|
||||
const auditing = list.filter((w) => w.status === 'auditing')
|
||||
expect(auditing.length).toBeGreaterThan(0)
|
||||
expect((await adminApi.handleWithdraw(auditing[0].id, 'pay')).status).toBe('paid')
|
||||
})
|
||||
|
||||
it('STEP14 订单退款 + 财务报表核对', async () => {
|
||||
expect((await adminApi.refund(3001, 5, '用户申请退款')).refunded).toBe(true)
|
||||
const report = await adminApi.financeReport('day')
|
||||
const netSum = report.rows.reduce((s, r) => s + r.net, 0)
|
||||
expect(netSum).toBeGreaterThan(0)
|
||||
expect((await adminApi.financeFlows({ page: 1, size: 50 })).total).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('STEP15 权限与系统设置收口', async () => {
|
||||
const superRole = (await adminApi.roles()).find((r) => r.name === '超级管理员')
|
||||
expect(superRole.permissions).toContain('*')
|
||||
|
||||
await expectReject(() => adminApi.saveDistSetting({ level1Rate: 90, level2Rate: 30 }), '不能超过 100%')
|
||||
expect((await adminApi.saveFeeSetting({ singlePost: 5 })).singlePost).toBe(5)
|
||||
expect((await adminApi.savePaySetting({ mchId: '1900000001', apiKey: 'secret' })).configured).toBe(true)
|
||||
expect((await adminApi.saveArea({ name: '乌当区' })).name).toBe('乌当区')
|
||||
expect((await adminApi.logs({ page: 1, size: 5 })).list.length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('边界与异常(软件测试视角)', () => {
|
||||
it('未匹配的接口返回 404 语义错误', async () => {
|
||||
const { matchMock } = await import('../common/mock/index.js')
|
||||
await expectReject(() => matchMock({ url: '/nope', method: 'GET' }), '未匹配到路由')
|
||||
})
|
||||
|
||||
it('分页边界:超出范围返回空列表而非报错', async () => {
|
||||
const res = await homeApi.feed({ page: 9999, size: 10 })
|
||||
expect(res.list).toHaveLength(0)
|
||||
expect(res.hasMore).toBe(false)
|
||||
})
|
||||
|
||||
it('空结果可正常返回(便于空状态渲染)', async () => {
|
||||
const res = await homeApi.feed({ keyword: '不存在的关键词XYZ' })
|
||||
expect(res.list).toHaveLength(0)
|
||||
expect(res.total).toBe(0)
|
||||
})
|
||||
|
||||
it('金额换算精度:分↔元无损', async () => {
|
||||
const { fen2yuan, yuan2fen } = await import('../common/utils/format.js')
|
||||
expect(fen2yuan(5)).toBe('0.05')
|
||||
expect(yuan2fen(19.9)).toBe(1990)
|
||||
expect(fen2yuan(yuan2fen(168))).toBe('168.00')
|
||||
})
|
||||
|
||||
it('工具函数:时间与手机号脱敏', async () => {
|
||||
const { maskPhone, fromNow, formatTime } = await import('../common/utils/format.js')
|
||||
expect(maskPhone('13988888888')).toBe('139****8888')
|
||||
expect(fromNow(new Date())).toBe('刚刚')
|
||||
expect(formatTime('2024-01-05T10:00:00')).toMatch(/^2024-01-05 10:00$/)
|
||||
})
|
||||
})
|
||||
|
||||
125
uniapp/tests/harness.mjs
普通文件
125
uniapp/tests/harness.mjs
普通文件
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* 极简测试框架(零依赖,兼容 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 }
|
||||
}
|
||||
178
uniapp/tests/icons.test.mjs
普通文件
178
uniapp/tests/icons.test.mjs
普通文件
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* LOGO 与图标自定义 测试
|
||||
* 覆盖:内置默认图 → 后台覆盖 → 用户端读取生效 的完整链路 + 资源文件完整性
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import url from 'node:url'
|
||||
import { describe, it, expect, expectReject } from './harness.mjs'
|
||||
import { ICON_GROUPS, ICON_DEFAULTS, ICON_BASE, CATEGORY_ICON_KEY, DEFAULT_LOGO } from '../common/assets/icons.js'
|
||||
import {
|
||||
iconUrl,
|
||||
logoUrl,
|
||||
categoryIconUrl,
|
||||
setRemoteUi,
|
||||
getRemoteUi,
|
||||
resetRemoteUi,
|
||||
isIconOverridden,
|
||||
} from '../common/utils/icon.js'
|
||||
import adminApi from '../common/api/admin.js'
|
||||
import { settingApi } from '../common/api/index.js'
|
||||
import { decodePng, transparentRatio } from '../tools/png-util.mjs'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '..')
|
||||
|
||||
describe('图标资源 · 文件完整性', () => {
|
||||
it('注册表中每个图标都有默认文件声明', () => {
|
||||
for (const g of ICON_GROUPS) {
|
||||
for (const it of g.items) {
|
||||
expect(it.key).toBeTruthy()
|
||||
expect(it.name).toBeTruthy()
|
||||
expect(ICON_DEFAULTS[it.key]).toBe(it.file)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('static/icons 下存在全部内置图标 PNG', () => {
|
||||
const dir = path.join(ROOT, 'static', 'icons')
|
||||
const missing = []
|
||||
for (const key of Object.keys(ICON_DEFAULTS)) {
|
||||
const f = path.join(dir, ICON_DEFAULTS[key])
|
||||
if (!fs.existsSync(f)) missing.push(ICON_DEFAULTS[key])
|
||||
}
|
||||
expect(missing).toEqual([])
|
||||
})
|
||||
|
||||
it('每个图标文件都是有效 PNG 且体积合理', () => {
|
||||
const dir = path.join(ROOT, 'static', 'icons')
|
||||
for (const key of Object.keys(ICON_DEFAULTS)) {
|
||||
const buf = fs.readFileSync(path.join(dir, ICON_DEFAULTS[key]))
|
||||
// PNG 魔数
|
||||
expect(buf.slice(0, 8).toString('hex')).toBe('89504e470d0a1a0a')
|
||||
expect(buf.length).toBeGreaterThan(300)
|
||||
}
|
||||
})
|
||||
|
||||
it('每个配图都具备真实的透明通道(左上角必须透明)', () => {
|
||||
// 回归防护:qlmanage 会把 SVG 合成到不透明白底上,
|
||||
// 必须经过「白底/黑底两遍渲染 + alpha 反解」,否则会出现白色方块。
|
||||
const dir = path.join(ROOT, 'static', 'icons')
|
||||
const opaque = []
|
||||
const lowAlpha = []
|
||||
for (const key of Object.keys(ICON_DEFAULTS)) {
|
||||
const img = decodePng(fs.readFileSync(path.join(dir, ICON_DEFAULTS[key])))
|
||||
if (img.rgba[3] !== 0) opaque.push(`${ICON_DEFAULTS[key]}(角点不透明)`)
|
||||
const ratio = transparentRatio(img)
|
||||
if (ratio < 0.02) lowAlpha.push(`${ICON_DEFAULTS[key]}(${ratio.toFixed(3)})`)
|
||||
}
|
||||
expect(opaque).toEqual([])
|
||||
expect(lowAlpha).toEqual([])
|
||||
})
|
||||
|
||||
it('配图尺寸统一且足够清晰(≥128px 方图)', () => {
|
||||
const dir = path.join(ROOT, 'static', 'icons')
|
||||
const sizes = new Set()
|
||||
for (const key of Object.keys(ICON_DEFAULTS)) {
|
||||
const img = decodePng(fs.readFileSync(path.join(dir, ICON_DEFAULTS[key])))
|
||||
expect(img.width).toBe(img.height)
|
||||
expect(img.width).toBeGreaterThan(127)
|
||||
sizes.add(img.width)
|
||||
}
|
||||
expect(sizes.size).toBe(1) // 全部同一尺寸,保证视觉一致
|
||||
})
|
||||
|
||||
it('品牌 LOGO 存在且为 PNG', () => {
|
||||
const logo = fs.readFileSync(path.join(ROOT, 'static', 'logo.png'))
|
||||
expect(logo.slice(0, 8).toString('hex')).toBe('89504e470d0a1a0a')
|
||||
expect(logo.length).toBeGreaterThan(1000)
|
||||
})
|
||||
|
||||
it('分类 ID 与分类图标 key 一一对应', () => {
|
||||
expect(Object.keys(CATEGORY_ICON_KEY)).toHaveLength(8)
|
||||
expect(ICON_DEFAULTS[CATEGORY_ICON_KEY[1]]).toBe('cat-job.png')
|
||||
expect(ICON_DEFAULTS[CATEGORY_ICON_KEY[8]]).toBe('cat-friend.png')
|
||||
})
|
||||
})
|
||||
|
||||
describe('图标解析 · 本地默认', () => {
|
||||
it('未配置时返回内置默认图地址', () => {
|
||||
resetRemoteUi()
|
||||
expect(iconUrl('tab-home')).toBe(`${ICON_BASE}tab-home.png`)
|
||||
expect(iconUrl('cat-job')).toBe(`${ICON_BASE}cat-job.png`)
|
||||
expect(logoUrl()).toBe(DEFAULT_LOGO)
|
||||
expect(categoryIconUrl(4)).toBe(`${ICON_BASE}cat-car.png`)
|
||||
})
|
||||
|
||||
it('未注册的 key 返回空字符串(不产生错误图片请求)', () => {
|
||||
resetRemoteUi()
|
||||
expect(iconUrl('not-exist-key')).toBe('')
|
||||
expect(iconUrl('')).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('图标解析 · 后台覆盖生效', () => {
|
||||
it('setRemoteUi 后按 key 覆盖为自定义地址', () => {
|
||||
setRemoteUi({
|
||||
logo: 'https://cdn.example.com/mylogo.png',
|
||||
icons: { 'tab-home': 'https://cdn.example.com/home.png' },
|
||||
})
|
||||
expect(iconUrl('tab-home')).toBe('https://cdn.example.com/home.png')
|
||||
expect(iconUrl('tab-mine')).toBe(`${ICON_BASE}tab-mine.png`) // 未覆盖的仍走默认
|
||||
expect(logoUrl()).toBe('https://cdn.example.com/mylogo.png')
|
||||
expect(isIconOverridden('tab-home')).toBe(true)
|
||||
expect(isIconOverridden('tab-mine')).toBe(false)
|
||||
})
|
||||
|
||||
it('分类图标被覆盖时随 key 一起生效', () => {
|
||||
setRemoteUi({ icons: { 'cat-car': 'https://cdn.example.com/car.png' } })
|
||||
expect(categoryIconUrl(4)).toBe('https://cdn.example.com/car.png')
|
||||
expect(categoryIconUrl(1)).toBe(`${ICON_BASE}cat-job.png`)
|
||||
})
|
||||
|
||||
it('resetRemoteUi 恢复内置默认', () => {
|
||||
resetRemoteUi()
|
||||
expect(getRemoteUi()).toEqual({ logo: '', icons: {} })
|
||||
expect(iconUrl('tab-home')).toBe(`${ICON_BASE}tab-home.png`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台接口 · LOGO 与图标自定义闭环', () => {
|
||||
it('STEP1 后台可读取当前 UI 配置', async () => {
|
||||
const cfg = await adminApi.uiSetting()
|
||||
expect(cfg.siteName).toBeDefined()
|
||||
expect(cfg.icons).toBeDefined()
|
||||
})
|
||||
|
||||
it('STEP2 后台保存 LOGO 与图标后,用户端接口读到相同内容', async () => {
|
||||
const saved = await adminApi.saveUiSetting({
|
||||
logo: 'https://cdn.example.com/logo-new.png',
|
||||
icons: { 'tab-home': 'https://cdn.example.com/h.png', 'cat-job': 'https://cdn.example.com/j.png' },
|
||||
})
|
||||
expect(saved.logo).toBe('https://cdn.example.com/logo-new.png')
|
||||
expect(saved.icons['tab-home']).toBe('https://cdn.example.com/h.png')
|
||||
|
||||
// 用户端读取
|
||||
const client = await settingApi.ui()
|
||||
expect(client.logo).toBe('https://cdn.example.com/logo-new.png')
|
||||
expect(client.icons['cat-job']).toBe('https://cdn.example.com/j.png')
|
||||
|
||||
// 应用到解析层
|
||||
setRemoteUi(client)
|
||||
expect(iconUrl('tab-home')).toBe('https://cdn.example.com/h.png')
|
||||
expect(logoUrl()).toBe('https://cdn.example.com/logo-new.png')
|
||||
})
|
||||
|
||||
it('STEP3 图标地址必须是字符串(类型校验)', async () => {
|
||||
await expectReject(() => adminApi.saveUiSetting({ icons: { 'tab-home': 123 } }), '必须是字符串')
|
||||
})
|
||||
|
||||
it('STEP4 恢复默认后用户端回到内置图', async () => {
|
||||
await adminApi.resetUiSetting()
|
||||
const client = await settingApi.ui()
|
||||
expect(client.logo).toBe('')
|
||||
expect(client.icons).toEqual({})
|
||||
setRemoteUi(client)
|
||||
expect(logoUrl()).toBe(DEFAULT_LOGO)
|
||||
expect(iconUrl('tab-home')).toBe(`${ICON_BASE}tab-home.png`)
|
||||
})
|
||||
})
|
||||
184
uniapp/tests/publish.test.mjs
普通文件
184
uniapp/tests/publish.test.mjs
普通文件
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* v1.0.7 新增能力用例:我的发布 / 后台手动置顶 / 免费-付费发布开关与套餐额度
|
||||
*
|
||||
* 覆盖需求:
|
||||
* ① 发布后能看到发布记录(/post/mine + 状态计数 + 驳回原因)
|
||||
* ② 后台手动置顶 → 用户端主页置顶优先展示(/home/feed)
|
||||
* ③ 发布模式开关(免费/付费)+ 单条价格 + 月卡/年卡价格与含发布条数
|
||||
* ④ 计费口径:金额只由后台配置决定,客户端传入的 amount 一律被忽略
|
||||
*/
|
||||
import { describe, it, expect, expectReject } from './harness.mjs'
|
||||
import { homeApi, postApi, memberApi } from '../common/api/index.js'
|
||||
import { datasets } from '../common/mock/data.js'
|
||||
|
||||
/** 每个用例前把 mock 状态复位,保证用例之间互不影响 */
|
||||
function resetPublish() {
|
||||
datasets.publishRule.mode = 'paid'
|
||||
datasets.publishRule.singlePrice = 5
|
||||
datasets.publishRule.monthPrice = 19.9
|
||||
datasets.publishRule.monthQuota = 30
|
||||
datasets.publishRule.yearPrice = 168
|
||||
datasets.publishRule.yearQuota = 500
|
||||
datasets.publishRule.quotaLeft = 30
|
||||
datasets.publishRule.freePerDay = 2
|
||||
datasets.publishRule.freeUsedToday = 0
|
||||
datasets.publishRule.isMember = true
|
||||
}
|
||||
|
||||
describe('发布配置 · 后台开关与价格下发', () => {
|
||||
it('返回发布模式、三档价格与剩余额度', async () => {
|
||||
resetPublish()
|
||||
const cfg = await postApi.publishConfig()
|
||||
expect(cfg.mode).toBe('paid')
|
||||
expect(cfg.singlePrice).toBe(5)
|
||||
expect(cfg.monthPrice).toBe(19.9)
|
||||
expect(cfg.monthQuota).toBe(30)
|
||||
expect(cfg.yearPrice).toBe(168)
|
||||
expect(cfg.yearQuota).toBe(500)
|
||||
expect(cfg.quotaLeft).toBe(30)
|
||||
expect(cfg.isMember).toBe(true)
|
||||
})
|
||||
|
||||
it('免费模式:所有人免费发布且不消耗额度', async () => {
|
||||
resetPublish()
|
||||
datasets.publishRule.mode = 'free'
|
||||
datasets.publishRule.quotaLeft = 0
|
||||
const res = await postApi.create({ title: '免费模式发布', content: '内容', plan: 'free' })
|
||||
expect(res.order).toBeFalsy()
|
||||
expect(res.plan).toBe('free')
|
||||
expect(res.amount).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('发布计费 · 服务端定价与套餐额度', () => {
|
||||
it('套餐额度内免费发布:无订单且额度 -1', async () => {
|
||||
resetPublish()
|
||||
const res = await postApi.create({ title: '额度内发布', content: '内容', plan: 'free' })
|
||||
expect(res.order).toBeFalsy()
|
||||
expect(res.plan).toBe('quota')
|
||||
expect(res.quotaLeft).toBe(29)
|
||||
const mine = await postApi.mine({ page: 1, size: 20 })
|
||||
const created = mine.list.find((p) => p.title === '额度内发布')
|
||||
expect(created).toBeDefined()
|
||||
expect(created.auditStatus).toBe(0)
|
||||
})
|
||||
|
||||
it('额度与每日免费次数都用尽时,免费发布被拦截', async () => {
|
||||
resetPublish()
|
||||
datasets.publishRule.quotaLeft = 0
|
||||
datasets.publishRule.freePerDay = 0 // 关闭每日免费额度,隔离出「必须付费」的场景
|
||||
await expectReject(() => postApi.create({ title: '无额度', content: '内容', plan: 'free' }), '请选择发布方式')
|
||||
})
|
||||
|
||||
it('付费模式下仍保留每日免费额度(避免硬付费墙)', async () => {
|
||||
resetPublish()
|
||||
datasets.publishRule.quotaLeft = 0
|
||||
datasets.publishRule.freePerDay = 2
|
||||
datasets.publishRule.freeUsedToday = 0
|
||||
const first = await postApi.create({ title: '今日免费第 1 条', content: '内容', plan: 'free' })
|
||||
expect(first.plan).toBe('free')
|
||||
expect(first.order).toBeFalsy()
|
||||
const cfg = await postApi.publishConfig()
|
||||
expect(cfg.freeLeftToday).toBe(1)
|
||||
const second = await postApi.create({ title: '今日免费第 2 条', content: '内容', plan: 'free' })
|
||||
expect(second.plan).toBe('free')
|
||||
// 第 3 条超出每日额度 → 必须付费
|
||||
await expectReject(() => postApi.create({ title: '超出每日额度', content: '内容', plan: 'free' }), '请选择发布方式')
|
||||
})
|
||||
|
||||
it('单条付费:金额取后台配置,忽略客户端传入的 amount', async () => {
|
||||
resetPublish()
|
||||
datasets.publishRule.quotaLeft = 0
|
||||
datasets.publishRule.freePerDay = 0
|
||||
const res = await postApi.create({
|
||||
title: '单条付费发布',
|
||||
content: '内容',
|
||||
plan: 'single',
|
||||
payType: 'wxpay',
|
||||
amount: 0.01, // 客户端篡改金额:应被无条件忽略
|
||||
})
|
||||
expect(res.order.amount).toBe(5)
|
||||
expect(res.order.orderNo).toContain('PO')
|
||||
})
|
||||
|
||||
it('单条付费缺少支付方式时报错', async () => {
|
||||
resetPublish()
|
||||
datasets.publishRule.quotaLeft = 0
|
||||
datasets.publishRule.freePerDay = 0
|
||||
await expectReject(() => postApi.create({ title: 'x', content: 'y', plan: 'single' }), '支付方式不支持')
|
||||
})
|
||||
|
||||
it('月卡/年卡走会员开通接口,开通后获得对应发布条数', async () => {
|
||||
resetPublish()
|
||||
datasets.publishRule.quotaLeft = 0
|
||||
datasets.publishRule.freePerDay = 0
|
||||
const opened = await memberApi.open({ planId: 'M1', payType: 'balance' })
|
||||
expect(opened.postQuota).toBe(30)
|
||||
expect(opened.quotaLeft).toBe(30)
|
||||
const res = await postApi.create({ title: '月卡额度发布', content: '内容', plan: 'free' })
|
||||
expect(res.plan).toBe('quota')
|
||||
expect(res.quotaLeft).toBe(29)
|
||||
// 年卡:含 500 条
|
||||
const year = await memberApi.open({ planId: 'M12', payType: 'balance' })
|
||||
expect(year.postQuota).toBe(500)
|
||||
expect(year.quotaLeft).toBe(529)
|
||||
})
|
||||
|
||||
it('会员套餐列表带出「含发布条数」字段', async () => {
|
||||
const plans = await memberApi.plans()
|
||||
expect(plans.length).toBe(3)
|
||||
plans.forEach((p) => expect(p.postQuota).toBeGreaterThan(0))
|
||||
})
|
||||
})
|
||||
|
||||
describe('我的发布 · 审核状态与计数', () => {
|
||||
it('列表返回本人信息与各状态计数', async () => {
|
||||
const res = await postApi.mine({ page: 1, size: 20 })
|
||||
expect(res.list.length).toBeGreaterThan(0)
|
||||
expect(res.counts.all).toBeGreaterThan(0)
|
||||
expect(res.counts.pending + res.counts.passed + res.counts.rejected).toBeGreaterThan(0)
|
||||
res.list.forEach((p) => {
|
||||
expect(p.auditStatus).toBeDefined()
|
||||
expect(p.status).toBeDefined()
|
||||
expect(p.isTop).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
it('按状态筛选:待审核 / 已驳回(含驳回原因)/ 已下架', async () => {
|
||||
const pending = await postApi.mine({ status: 'pending' })
|
||||
expect(pending.list.every((p) => p.auditStatus === 0 && p.status === 1)).toBe(true)
|
||||
|
||||
const rejected = await postApi.mine({ status: 'rejected' })
|
||||
expect(rejected.list.every((p) => p.auditStatus === 2)).toBe(true)
|
||||
expect(rejected.list[0].auditReason).toBeTruthy()
|
||||
|
||||
const offline = await postApi.mine({ status: 'offline' })
|
||||
expect(offline.list.every((p) => p.status === 0)).toBe(true)
|
||||
})
|
||||
|
||||
it('置顶的发布记录排在最前', async () => {
|
||||
const res = await postApi.mine({ page: 1, size: 20 })
|
||||
expect(res.list[0].isTop).toBe(true)
|
||||
})
|
||||
|
||||
it('可删除本人发布(删除后列表不再包含)', async () => {
|
||||
const before = await postApi.mine({ page: 1, size: 20 })
|
||||
const target = before.list[0]
|
||||
await postApi.remove(target.id)
|
||||
const after = await postApi.mine({ page: 1, size: 20 })
|
||||
expect(after.counts.all).toBe(before.counts.all - 1)
|
||||
expect(after.list.some((p) => p.id === target.id)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('后台置顶 → 用户端展示闭环', () => {
|
||||
it('置顶信息在首页信息流优先展示', async () => {
|
||||
const feed = await homeApi.feed({ page: 1, size: 10 })
|
||||
expect(feed.list[0].isTop).toBe(true)
|
||||
// 置顶项之后才是非置顶项
|
||||
const firstUnpinned = feed.list.findIndex((p) => !p.isTop)
|
||||
if (firstUnpinned > -1) {
|
||||
expect(feed.list.slice(firstUnpinned).every((p) => !p.isTop)).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
134
uniapp/tests/request.test.mjs
普通文件
134
uniapp/tests/request.test.mjs
普通文件
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* 请求层(全链路统一网关)测试
|
||||
* 覆盖:URL 拼接 / 鉴权头 / 业务码解包 / 401 / 网络异常 / mock 降级
|
||||
*/
|
||||
import { describe, it, expect, expectReject } from './harness.mjs'
|
||||
import config from '../common/config/index.js'
|
||||
import storage from '../common/utils/storage.js'
|
||||
import request, { get, post, buildUrl, buildHeaders, getRuntime } from '../common/utils/request.js'
|
||||
|
||||
/** 构造一个可控的 uni 运行时 */
|
||||
function installUni(handler) {
|
||||
const calls = { toasts: [], navigations: [], requests: [] }
|
||||
globalThis.uni = {
|
||||
request(opts) {
|
||||
calls.requests.push(opts)
|
||||
handler(opts, calls)
|
||||
},
|
||||
showToast(o) {
|
||||
calls.toasts.push(o)
|
||||
},
|
||||
navigateTo(o) {
|
||||
calls.navigations.push(o)
|
||||
},
|
||||
getStorageSync: () => '',
|
||||
setStorageSync: () => {},
|
||||
removeStorageSync: () => {},
|
||||
}
|
||||
return calls
|
||||
}
|
||||
|
||||
function clearUni() {
|
||||
delete globalThis.uni
|
||||
}
|
||||
|
||||
describe('请求层 · 基础能力', () => {
|
||||
it('buildUrl 拼接版本号与网关地址', () => {
|
||||
expect(buildUrl('/home/feed')).toBe(`${config.baseURL}/${config.apiVersion}/home/feed`)
|
||||
expect(buildUrl('post/create')).toContain('/v1/post/create')
|
||||
expect(buildUrl('https://a.com/x')).toBe('https://a.com/x')
|
||||
})
|
||||
|
||||
it('buildHeaders 注入 token 与客户端标识', () => {
|
||||
storage.clear()
|
||||
storage.set(config.storageKeys.token, 'T-123')
|
||||
const h = buildHeaders()
|
||||
expect(h.Authorization).toBe('Bearer T-123')
|
||||
expect(h['X-Client']).toBe('fenleixinxi')
|
||||
storage.remove(config.storageKeys.token)
|
||||
expect(buildHeaders().Authorization).toBeFalsy()
|
||||
})
|
||||
|
||||
it('无 uni.request 时自动走 mock(离线可运行)', async () => {
|
||||
clearUni()
|
||||
const data = await get('/home/categories')
|
||||
expect(data).toBeArray()
|
||||
expect(data.length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('请求层 · 真实 HTTP 通道', () => {
|
||||
it('业务码 0 时返回 data 字段', async () => {
|
||||
const calls = installUni((opts) => {
|
||||
opts.success({ statusCode: 200, data: { code: 0, message: 'ok', data: { total: 7 } } })
|
||||
})
|
||||
const res = await get('/home/feed', { page: 1 })
|
||||
expect(res.total).toBe(7)
|
||||
expect(calls.requests[0].url).toContain('/v1/home/feed')
|
||||
clearUni()
|
||||
})
|
||||
|
||||
it('业务码非 0 时 reject 并 toast 提示', async () => {
|
||||
const calls = installUni((opts) => {
|
||||
opts.success({ statusCode: 200, data: { code: 1001, message: '参数错误' } })
|
||||
})
|
||||
await expectReject(() => post('/post/create', { title: '' }), '参数错误')
|
||||
expect(calls.toasts[0].title).toBe('参数错误')
|
||||
clearUni()
|
||||
})
|
||||
|
||||
it('HTTP 401 清空登录态并跳转登录页', async () => {
|
||||
storage.set(config.storageKeys.token, 'EXPIRED')
|
||||
const calls = installUni((opts) => opts.success({ statusCode: 401, data: {} }))
|
||||
await expectReject(() => get('/auth/profile'), '登录已过期')
|
||||
expect(storage.get(config.storageKeys.token, '')).toBe('')
|
||||
expect(calls.navigations[0].url).toBe('/pages/auth/login')
|
||||
clearUni()
|
||||
})
|
||||
|
||||
it('显式开启 enableMockFallback 时,网络异常且存在 mock 路由则自动降级', async () => {
|
||||
const saved = config.enableMockFallback
|
||||
config.enableMockFallback = true
|
||||
const calls = installUni((opts) => opts.fail({ errMsg: 'request:fail timeout' }))
|
||||
const res = await get('/member/plans')
|
||||
expect(res).toBeArray()
|
||||
expect(res[0].planId).toBeDefined()
|
||||
clearUni()
|
||||
config.enableMockFallback = saved
|
||||
})
|
||||
|
||||
// 生产配置下必须关闭降级:否则真实接口失败会静默返回 mock 假数据,
|
||||
// 表现为「后台改了但前端不变」,且真实问题被完全掩盖。
|
||||
it('生产配置(enableMockFallback=false)网络异常时不静默返回 mock 数据', async () => {
|
||||
expect(config.forceMock).toBe(false)
|
||||
expect(config.enableMockFallback).toBe(false)
|
||||
installUni((opts) => opts.fail({ errMsg: 'request:fail timeout' }))
|
||||
await expectReject(() => get('/member/plans'), 'request:fail')
|
||||
clearUni()
|
||||
})
|
||||
|
||||
it('网络异常且无 mock 路由时抛出异常', async () => {
|
||||
installUni((opts) => opts.fail({ errMsg: 'request:fail' }))
|
||||
await expectReject(() => get('/not/exist/endpoint'), 'request:fail')
|
||||
clearUni()
|
||||
})
|
||||
|
||||
it('getRuntime 在无 uni 环境返回安全降级函数', () => {
|
||||
clearUni()
|
||||
const rt = getRuntime()
|
||||
expect(rt.request).toBe(null)
|
||||
rt.showToast({ title: 'x' }) // 不应抛错
|
||||
})
|
||||
})
|
||||
|
||||
describe('请求层 · mock 强制模式', () => {
|
||||
it('mock:true 时绕过网络直接返回 mock 数据', async () => {
|
||||
const calls = installUni(() => {
|
||||
throw new Error('不应发起真实请求')
|
||||
})
|
||||
const res = await request({ url: '/home/banners', mock: true })
|
||||
expect(res).toBeArray()
|
||||
expect(calls.requests).toHaveLength(0)
|
||||
clearUni()
|
||||
})
|
||||
})
|
||||
18
uniapp/tests/run.mjs
普通文件
18
uniapp/tests/run.mjs
普通文件
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 测试入口
|
||||
* 运行: node tests/run.mjs
|
||||
* (本机未安装 Node 时,可使用 HBuilderX 内置 Node:
|
||||
* /Applications/HBuilderX.app/Contents/HBuilderX/plugins/node/node tests/run.mjs)
|
||||
*/
|
||||
import { run } from './harness.mjs'
|
||||
|
||||
// 载入全部测试用例(import 时完成用例注册)
|
||||
await import('./request.test.mjs')
|
||||
await import('./icons.test.mjs')
|
||||
await import('./banners.test.mjs')
|
||||
await import('./api.user.contract.test.mjs')
|
||||
await import('./api.admin.contract.test.mjs')
|
||||
await import('./publish.test.mjs')
|
||||
await import('./e2e.flow.test.mjs')
|
||||
|
||||
await run()
|
||||
27
uniapp/tests/run.sh
可执行文件
27
uniapp/tests/run.sh
可执行文件
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# 全链路接口测试 + 项目结构校验 一键执行脚本
|
||||
# 优先使用系统 node,缺失时回退到 HBuilderX 内置 Node(macOS)。
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if command -v node >/dev/null 2>&1; then
|
||||
NODE=node
|
||||
elif [ -x "/Applications/HBuilderX.app/Contents/HBuilderX/plugins/node/node" ]; then
|
||||
NODE="/Applications/HBuilderX.app/Contents/HBuilderX/plugins/node/node"
|
||||
else
|
||||
echo "未找到可用的 Node 运行时,请安装 Node 18+ 或 HBuilderX。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "使用 Node: $NODE ($($NODE -v))"
|
||||
|
||||
echo ""
|
||||
echo ">>> [1/3] 项目结构校验"
|
||||
"$NODE" tests/validate.mjs
|
||||
|
||||
echo ""
|
||||
echo ">>> [2/3] SCSS 编译校验(dart-sass)"
|
||||
"$NODE" tools/check-scss.cjs
|
||||
|
||||
echo ""
|
||||
echo ">>> [3/3] 全链路接口测试"
|
||||
"$NODE" tests/run.mjs
|
||||
202
uniapp/tests/validate.mjs
普通文件
202
uniapp/tests/validate.mjs
普通文件
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* 静态校验脚本(结构体检)
|
||||
* 校验内容:
|
||||
* 1. pages.json 中声明的页面文件是否存在
|
||||
* 2. 每个 .vue 是否包含成对的 <template>/<script>/<style>
|
||||
* 3. <style> 块内大括号是否配平(SCSS 语法粗略校验)
|
||||
* 4. .vue 文件里 import 的本地模块是否存在
|
||||
* 运行: node tests/validate.mjs
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import url from 'node:url'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
|
||||
const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
|
||||
const ROOT = path.resolve(__dirname, '..')
|
||||
|
||||
let errors = 0
|
||||
let warns = 0
|
||||
const ok = (m) => console.log(` ✅ ${m}`)
|
||||
const bad = (m) => {
|
||||
errors++
|
||||
console.log(` ❌ ${m}`)
|
||||
}
|
||||
const warn = (m) => {
|
||||
warns++
|
||||
console.log(` ⚠️ ${m}`)
|
||||
}
|
||||
|
||||
function readJsonLoose(p) {
|
||||
const raw = fs.readFileSync(p, 'utf8')
|
||||
return JSON.parse(raw.replace(/\/\/.*$/gm, ''))
|
||||
}
|
||||
|
||||
function walk(dir, ext, out = []) {
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
if (name === 'node_modules' || name === '.git' || name === 'unpackage') continue
|
||||
const full = path.join(dir, name)
|
||||
const st = fs.statSync(full)
|
||||
if (st.isDirectory()) walk(full, ext, out)
|
||||
else if (name.endsWith(ext)) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
console.log('\n=========== 项目结构校验 ===========')
|
||||
|
||||
// 1. pages.json 页面存在性
|
||||
console.log('\n[1] pages.json 页面文件存在性')
|
||||
const pagesJson = readJsonLoose(path.join(ROOT, 'pages.json'))
|
||||
for (const p of pagesJson.pages) {
|
||||
const file = path.join(ROOT, p.path + '.vue')
|
||||
if (fs.existsSync(file)) ok(`${p.path}.vue`)
|
||||
else bad(`缺失页面文件: ${p.path}.vue`)
|
||||
}
|
||||
|
||||
// 2 & 3. vue 结构与大括号配平
|
||||
console.log('\n[2] .vue 结构(template/script/style)与大括号配平')
|
||||
const vues = walk(ROOT, '.vue')
|
||||
for (const f of vues) {
|
||||
const rel = path.relative(ROOT, f)
|
||||
const src = fs.readFileSync(f, 'utf8')
|
||||
const tOpen = (src.match(/<template>/g) || []).length
|
||||
const tClose = (src.match(/<\/template>/g) || []).length
|
||||
const sOpen = (src.match(/<script>/g) || []).length
|
||||
const sClose = (src.match(/<\/script>/g) || []).length
|
||||
const yOpen = (src.match(/<style[^>]*>/g) || []).length
|
||||
const yClose = (src.match(/<\/style>/g) || []).length
|
||||
|
||||
if (tOpen !== tClose || sOpen !== sClose || yOpen !== yClose) {
|
||||
bad(`${rel} 标签不配对 template(${tOpen}/${tClose}) script(${sOpen}/${sClose}) style(${yOpen}/${yClose})`)
|
||||
continue
|
||||
}
|
||||
if (sOpen !== 1 || yOpen !== 1 || (tOpen !== 1 && path.basename(f) !== 'App.vue')) {
|
||||
warn(`${rel} 标签数量异常(可能为多根节点)`)
|
||||
}
|
||||
|
||||
// style 块大括号配平
|
||||
const styleMatch = src.match(/<style[^>]*>([\s\S]*)<\/style>/)
|
||||
if (styleMatch) {
|
||||
const css = styleMatch[1]
|
||||
let depth = 0
|
||||
let minDepth = 0
|
||||
for (const ch of css) {
|
||||
if (ch === '{') depth++
|
||||
else if (ch === '}') {
|
||||
depth--
|
||||
if (depth < minDepth) minDepth = depth
|
||||
}
|
||||
}
|
||||
if (depth !== 0 || minDepth < 0) bad(`${rel} <style> 大括号不配平(depth=${depth}, min=${minDepth})`)
|
||||
else ok(`${rel}`)
|
||||
} else {
|
||||
ok(`${rel}(无 style)`)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. import 相对/别名路径存在性
|
||||
console.log('\n[3] import 依赖存在性(@/ 与 相对路径)')
|
||||
const jsFiles = [...walk(ROOT, '.js'), ...walk(ROOT, '.mjs'), ...vues]
|
||||
for (const f of jsFiles) {
|
||||
if (f.includes(path.join('tests', 'validate.mjs'))) continue
|
||||
const src = fs.readFileSync(f, 'utf8')
|
||||
const rel = path.relative(ROOT, f)
|
||||
const re = /from\s+['"]([^'"]+)['"]/g
|
||||
let m
|
||||
while ((m = re.exec(src))) {
|
||||
const spec = m[1]
|
||||
if (!spec.startsWith('.') && !spec.startsWith('@/')) continue // 第三方包跳过
|
||||
let target = spec.startsWith('@/')
|
||||
? path.join(ROOT, spec.slice(2))
|
||||
: path.resolve(path.dirname(f), spec)
|
||||
const candidates = [target, target + '.js', target + '.mjs', target + '.vue', path.join(target, 'index.js')]
|
||||
if (!candidates.some((c) => fs.existsSync(c))) bad(`${rel} → 找不到依赖 "${spec}"`)
|
||||
}
|
||||
}
|
||||
ok('依赖检查完成')
|
||||
|
||||
// 5. <script> JS 语法校验(node --check)
|
||||
console.log('\n[4] <script> JS 语法校验')
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'fc-check-'))
|
||||
for (const f of vues) {
|
||||
const rel = path.relative(ROOT, f)
|
||||
const m = fs.readFileSync(f, 'utf8').match(/<script>([\s\S]*?)<\/script>/)
|
||||
if (!m) continue
|
||||
const tmp = path.join(tmpDir, path.basename(f).replace(/\.vue$/, '') + '.mjs')
|
||||
fs.writeFileSync(tmp, m[1], 'utf8')
|
||||
try {
|
||||
execFileSync(process.execPath, ['--check', tmp], { stdio: 'pipe' })
|
||||
ok(`${rel} <script>`)
|
||||
} catch (e) {
|
||||
const msg = String(e.stderr || e.message).split('\n').find((l) => l.includes('Error')) || 'SyntaxError'
|
||||
bad(`${rel} <script> 语法错误 → ${msg.trim()}`)
|
||||
}
|
||||
}
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
|
||||
// 6. 模板标签配平(模拟 WXML 结构校验)
|
||||
console.log('\n[5] <template> 标签配平(WXML 结构)')
|
||||
const VOID_TAGS = new Set(['input', 'br', 'img', 'slot'])
|
||||
for (const f of vues) {
|
||||
const rel = path.relative(ROOT, f)
|
||||
const src = fs.readFileSync(f, 'utf8')
|
||||
const tm = src.match(/<template>([\s\S]*)<\/template>/)
|
||||
if (!tm) continue
|
||||
const body = tm[1]
|
||||
const stack = []
|
||||
const re = /<(\/?)([a-zA-Z][\w-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/g
|
||||
let m
|
||||
let err = null
|
||||
while ((m = re.exec(body))) {
|
||||
const closing = m[1] === '/'
|
||||
const tag = m[2]
|
||||
const selfClose = m[4] === '/'
|
||||
if (selfClose || VOID_TAGS.has(tag)) continue
|
||||
if (!closing) {
|
||||
stack.push(tag)
|
||||
} else {
|
||||
const top = stack.pop()
|
||||
if (top !== tag) {
|
||||
err = `标签不匹配:</${tag}> 对应 <${top || '空'}>`
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (err) bad(`${rel} → ${err}`)
|
||||
else if (stack.length) bad(`${rel} → 未闭合标签:<${stack.join('>, <')}>`)
|
||||
else ok(`${rel}`)
|
||||
}
|
||||
|
||||
// 6. 禁止把「URL / 路径类字段」用 <text> 裸输出
|
||||
// 踩坑记录:pages/post/create.vue 曾用 <text>{{ c.icon }}</text> 渲染分类图标,
|
||||
// 而接口返回的 icon 是图片地址(/static/icons/cat-job.png),
|
||||
// 结果把路径当文字打印出来(8 条路径重叠)。此类字段必须用 <image :src>。
|
||||
// 判定口径:只报「裸字段输出」;
|
||||
// 若表达式中含字符串字面量(如 '当前:' + x),说明是刻意带标签展示,不报。
|
||||
console.log('\n[6] URL/路径字段误用 <text> 裸输出')
|
||||
const TEXT_INTERP_RE = /<text\b[^>]*>\s*\{\{([^}]*)\}\}\s*<\/text>/g
|
||||
const URL_FIELD_WORD = /\.(?:icon|iconKey|cover|logo|avatar|image|poster|posterUrl)\b/
|
||||
let urlFieldHits = 0
|
||||
for (const f of vues) {
|
||||
const rel = path.relative(ROOT, f)
|
||||
const src = fs.readFileSync(f, 'utf8')
|
||||
const tm = src.match(/<template>([\s\S]*)<\/template>/)
|
||||
if (!tm) continue
|
||||
let m
|
||||
TEXT_INTERP_RE.lastIndex = 0
|
||||
while ((m = TEXT_INTERP_RE.exec(tm[1]))) {
|
||||
const expr = m[1].trim()
|
||||
if (!URL_FIELD_WORD.test(expr)) continue
|
||||
if (/['"]/.test(expr)) continue
|
||||
urlFieldHits++
|
||||
bad(`${rel} → 把 URL 字段当文本输出:${m[0].replace(/\s+/g, ' ').slice(0, 80)}`)
|
||||
}
|
||||
}
|
||||
if (!urlFieldHits) ok('未发现把 URL/路径字段用 <text> 裸输出的地方')
|
||||
|
||||
console.log('\n------------------------------------------')
|
||||
console.log(`结构校验结束:错误 ${errors},警告 ${warns}`)
|
||||
console.log('------------------------------------------\n')
|
||||
if (errors) process.exitCode = 1
|
||||
在新工单中引用
屏蔽一个用户