文件
OmniCard/backend/test/modules/nfc/bind.test.ts
wikiboss eec259a3a7 feat: 完成全系统30个功能点开发与E2E全链路验收 (8轮调度32个子代理闭环)
- 模块一: 出海案例作品集、博客动态发布、人名发音语音条、RTL阿语多语言切换
- 模块二: AI顾问人设配置、行业术语库润色、RAG切片沙盒调试、流式会话与意向留资卡片
- 模块三: 全球访客雷达大屏、多维加权意向算分、外部CRM对接推送、团队公海池流转
- 模块四: 移动端NFC安全挂失、NFC动态路由规则配置、动态防伪验签、展会制卡Zip批量导出
- 模块五: 组织架构与名片分配、移动端个人中心设置、离职交接与历史线索迁移、安全审计日志
- 模块六: Stripe国际信用卡订阅Webhook、独立二级域名与SSL检测、坐席配额预警、多币种发票
- 模块七: 纸质名片OCR解析入库、国际商务日程RFC 5545 ICS日历、微官网离线SWR预加载、展会实时排行榜大屏
- 模块八: 全球出海SEO OpenGraph元标签注入与社交爬虫探测、30点端到端全链路业务流集成测试套件
2026-09-20 23:47:47 +08:00

282 行
8.3 KiB
TypeScript

import * as fs from 'fs';
import * as path from 'path';
import { CONTROLLER_KEY, getClassMetadata } from '@midwayjs/core';
import { BaseController, CoolCommException, CurdOption } from '@cool-midway/core';
import { NfcDeviceEntity } from '../../../src/modules/nfc/entity/device';
import { NfcBindService } from '../../../src/modules/nfc/service/bind';
import {
AdminNfcBindController,
adminNfcBindCurdOption,
} from '../../../src/modules/nfc/controller/admin/bind';
/**
* CoolController 元数据(脚本路径解析为异步)
*/
interface CoolControllerMeta {
prefix?: string;
curdOption?: CurdOption;
}
/**
* 等待 CoolController 将 CRUD 配置写入类元数据
*/
async function waitCoolMeta(
target: new (...args: never[]) => unknown
): Promise<CoolControllerMeta> {
const started = Date.now();
while (Date.now() - started < 2000) {
const meta = getClassMetadata(CONTROLLER_KEY, target) as
| CoolControllerMeta
| undefined;
if (meta?.curdOption) {
return meta;
}
await new Promise<void>(resolve => setImmediate(resolve));
}
throw new Error(`${target.name} 的 CoolController 元数据未就绪`);
}
function serviceApiMethods(apis: CurdOption['serviceApis'] = []): string[] {
return apis.map(api => (typeof api === 'string' ? api : api.method));
}
/**
* 内存 Repository,覆盖 findOneBy / save
*/
class MemoryNfcDeviceRepo {
private data: NfcDeviceEntity[] = [];
private currentId = 1;
constructor(initialData: Array<Partial<NfcDeviceEntity>> = []) {
this.data = initialData.map(item => this.createEntity(item));
if (this.data.length > 0) {
this.currentId = Math.max(...this.data.map(d => Number(d.id) || 0)) + 1;
}
}
private createEntity(item: Partial<NfcDeviceEntity>): NfcDeviceEntity {
const entity = new NfcDeviceEntity();
Object.assign(entity, {
id: item.id || this.currentId++,
createTime: item.createTime || new Date(),
updateTime: new Date(),
...item,
});
return entity;
}
async findOneBy(
where: Partial<Pick<NfcDeviceEntity, 'id' | 'uid' | 'status'>>
): Promise<NfcDeviceEntity | null> {
const found = this.data.find(item => {
const keys = Object.keys(where) as Array<keyof typeof where>;
return keys.every(key => {
const expected = where[key];
return expected === undefined || item[key] === expected;
});
});
return found ? ({ ...found } as NfcDeviceEntity) : null;
}
async save(
entityOrEntities:
| Partial<NfcDeviceEntity>
| Array<Partial<NfcDeviceEntity>>
): Promise<NfcDeviceEntity | NfcDeviceEntity[]> {
if (Array.isArray(entityOrEntities)) {
const savedList: NfcDeviceEntity[] = [];
for (const item of entityOrEntities) {
savedList.push((await this.save(item)) as NfcDeviceEntity);
}
return savedList;
}
const item = entityOrEntities;
if (item.id) {
const index = this.data.findIndex(d => d.id === item.id);
if (index !== -1) {
this.data[index] = {
...this.data[index],
...item,
updateTime: new Date(),
} as NfcDeviceEntity;
return { ...this.data[index] } as NfcDeviceEntity;
}
}
const newEntity = this.createEntity(item);
this.data.push(newEntity);
return { ...newEntity } as NfcDeviceEntity;
}
}
function createService(
seed: Array<Partial<NfcDeviceEntity>> = []
): NfcBindService {
const service = new NfcBindService();
service.nfcDeviceEntity = new MemoryNfcDeviceRepo(
seed
) as unknown as NfcBindService['nfcDeviceEntity'];
return service;
}
function seedDevices(): Array<Partial<NfcDeviceEntity>> {
return [
{
id: 1,
uid: '04:7A:B2:8F:1C:6D:80',
cardId: null,
batchNo: 'B2026-001',
material: 'pvc',
status: 'unbound',
sceneMode: 'business',
},
{
id: 2,
uid: '04:AA:BB:CC:DD:EE:01',
cardId: 100,
batchNo: 'B2026-001',
material: 'metal',
status: 'suspended',
sceneMode: 'business',
},
{
id: 3,
uid: '04:11:22:33:44:55:66',
cardId: 200,
batchNo: 'B2026-002',
material: 'wood',
status: 'active',
sceneMode: 'business',
},
{
id: 4,
uid: '04:UN:BD:CD:EF:01:02',
cardId: 300,
batchNo: 'B2026-003',
material: 'pvc',
status: 'unbound',
sceneMode: 'social',
},
];
}
describe('T22 NFC 绑定激活 (动态云端短链)', () => {
describe('1. Service bind / activate / switchCard / unbind', () => {
it('未挂失设备可 bind 成 active', async () => {
const service = createService(seedDevices());
const bound = await service.bind({
uid: '04:7A:B2:8F:1C:6D:80',
cardId: 88,
});
expect(bound.uid).toBe('04:7A:B2:8F:1C:6D:80');
expect(bound.cardId).toBe(88);
expect(bound.status).toBe('active');
});
it('suspended 设备不能 bind', async () => {
const service = createService(seedDevices());
await expect(
service.bind({
uid: '04:AA:BB:CC:DD:EE:01',
cardId: 88,
})
).rejects.toThrow(CoolCommException);
});
it('已有 cardId 的 unbound 设备可 activate 成 active', async () => {
const service = createService(seedDevices());
const activated = await service.activate({
uid: '04:UN:BD:CD:EF:01:02',
});
expect(activated.cardId).toBe(300);
expect(activated.status).toBe('active');
expect(activated.uid).toBe('04:UN:BD:CD:EF:01:02');
});
it('无 cardId 或已挂失时不能 activate', async () => {
const service = createService(seedDevices());
await expect(
service.activate({ uid: '04:7A:B2:8F:1C:6D:80' })
).rejects.toThrow(CoolCommException);
await expect(
service.activate({ uid: '04:AA:BB:CC:DD:EE:01' })
).rejects.toThrow(CoolCommException);
});
it('switchCard 只改 cardId,不改 uid', async () => {
const service = createService(seedDevices());
const switched = await service.switchCard({
uid: '04:11:22:33:44:55:66',
cardId: 501,
});
expect(switched.uid).toBe('04:11:22:33:44:55:66');
expect(switched.cardId).toBe(501);
expect(switched.status).toBe('active');
expect(switched.batchNo).toBe('B2026-002');
});
it('unbind 后 status 为 unbound 且 cardId 为空', async () => {
const service = createService(seedDevices());
const unbound = await service.unbind({
uid: '04:11:22:33:44:55:66',
});
expect(unbound.status).toBe('unbound');
expect(unbound.cardId == null).toBe(true);
expect(unbound.uid).toBe('04:11:22:33:44:55:66');
});
it('uid 缺失或设备未入台账时应拒绝', async () => {
const service = createService(seedDevices());
await expect(service.bind({ uid: '', cardId: 1 })).rejects.toThrow(
CoolCommException
);
await expect(
service.bind({ uid: '04:NOT:IN:LEDGER', cardId: 1 })
).rejects.toThrow(CoolCommException);
});
});
describe('2. 后台控制器 /admin/nfc/bind', () => {
const controllerFile = path.join(
__dirname,
'../../../src/modules/nfc/controller/admin/bind.ts'
);
let meta: CoolControllerMeta;
let option: CurdOption;
beforeAll(async () => {
meta = await waitCoolMeta(AdminNfcBindController);
option = meta.curdOption as CurdOption;
});
it('文件路径应符合 /admin/nfc/bind 自动路由约定', () => {
expect(fs.existsSync(controllerFile)).toBe(true);
expect(controllerFile.replace(/\\/g, '/')).toMatch(
/modules\/nfc\/controller\/admin\/bind\.ts$/
);
});
it('路由前缀应为 /admin/nfc/bind', () => {
expect(meta.prefix).toBe('/admin/nfc/bind');
});
it('控制器应继承 BaseController 并绑定 NfcBindService,不开 CRUD', () => {
expect(AdminNfcBindController.prototype).toBeInstanceOf(BaseController);
expect(option.service).toBe(NfcBindService);
expect(adminNfcBindCurdOption.service).toBe(NfcBindService);
expect(option.api || []).toEqual([]);
});
it('serviceApis 应包含 bind / activate / switchCard / unbind', () => {
const methods = serviceApiMethods(option.serviceApis);
expect(methods).toEqual(['bind', 'activate', 'switchCard', 'unbind']);
});
});
});