GuDingZiChan/print-agent/tests/api-client.test.mjs
WuYongJie 0dc3c09315 feat(资产与打印): 提交近期借还盘点与打印助手源码
- 提交借用单缺失异常处理、扫码借还搜索与站内消息快捷处理源码
- 提交盘点范围、多终端打印、组织同步与认证模式相关源码
- 提交 .NET/Node 打印助手及版本清单源码
2026-03-27 20:18:31 +08:00

116 lines
3.3 KiB
JavaScript

import test from 'node:test'
import assert from 'node:assert/strict'
import { createPrintAgentClient } from '../src/services/apiClient.js'
test('createPrintAgentClient 会用配对码请求长期令牌', async () => {
const calls = []
const client = createPrintAgentClient({
serverUrl: 'https://asset.example.com/',
fetchImpl: async (url, options) => {
calls.push({ url, options })
return {
ok: true,
async json() {
return {
code: 200,
message: '打印终端配对成功',
data: {
terminal_id: 12,
device_token: 'token-123'
}
}
}
}
}
})
const result = await client.pair({
pairCode: 'ABCD-EFGH',
terminalName: '前台标签机',
machineName: 'DESKTOP-001',
platform: 'win32'
})
assert.equal(calls[0].url, 'https://asset.example.com/api/print-agent/pair')
assert.equal(calls[0].options.method, 'POST')
assert.match(calls[0].options.body, /"code":"ABCD-EFGH"/)
assert.match(calls[0].options.body, /"terminal_name":"前台标签机"/)
assert.match(calls[0].options.body, /"machine_name":"DESKTOP-001"/)
assert.equal(result.terminal_id, 12)
assert.equal(result.device_token, 'token-123')
})
test('已配对请求会自动带上终端令牌', async () => {
const calls = []
const client = createPrintAgentClient({
serverUrl: 'https://asset.example.com',
getDeviceToken: () => 'token-xyz',
fetchImpl: async (url, options) => {
calls.push({ url, options })
return {
ok: true,
async json() {
return {
code: 200,
message: '领取成功',
data: {
job: {
id: 18,
status: 'claimed'
}
}
}
}
}
}
})
await client.claimNextJob({
terminalId: 7
})
assert.equal(calls[0].url, 'https://asset.example.com/api/print-agent/jobs/claim')
assert.equal(calls[0].options.headers.Authorization, 'Bearer token-xyz')
assert.match(calls[0].options.body, /"terminal_id":7/)
})
test('心跳会把字段转成后端要求的 snake_case', async () => {
const calls = []
const client = createPrintAgentClient({
serverUrl: 'https://asset.example.com',
getDeviceToken: () => 'token-xyz',
fetchImpl: async (url, options) => {
calls.push({ url, options })
return {
ok: true,
async json() {
return {
code: 200,
message: '心跳已接收',
data: {
id: 9
}
}
}
}
}
})
await client.sendHeartbeat({
terminalName: '行政标签机',
machineName: 'DESKTOP-001',
selectedPrinterName: 'Xprinter XP-420B',
printerSnapshot: [{ name: 'Xprinter XP-420B' }],
labelProfile: {
paper_size: '60x40mm'
}
})
assert.equal(calls[0].url, 'https://asset.example.com/api/print-agent/heartbeat')
assert.match(calls[0].options.body, /"terminal_name":"行政标签机"/)
assert.match(calls[0].options.body, /"machine_name":"DESKTOP-001"/)
assert.match(calls[0].options.body, /"selected_printer_name":"Xprinter XP-420B"/)
assert.match(calls[0].options.body, /"printer_snapshot":\[\{"name":"Xprinter XP-420B"\}\]/)
})