gongxiangp2/lib/__tests__/youyidian-notification-center.test.ts

70 lines
2.2 KiB
TypeScript

/** @jest-environment node */
import { randomUUID } from 'node:crypto'
import { submitYouyidianNotification } from '@/lib/youyidian-notification-center'
describe('由壹点通知中心客户端', () => {
const notifyOrigin = ['https:', '', 'notify.invalid'].join('/')
beforeEach(() => {
jest.replaceProperty(process, 'env', {
...process.env,
YYD_NOTIFICATION_CENTER_URL: notifyOrigin,
YYD_NOTIFICATION_CENTER_PROJECT_CODE: 'test-project',
YYD_NOTIFICATION_CENTER_PROJECT_SECRET: randomUUID(),
})
})
afterEach(() => {
jest.restoreAllMocks()
jest.useRealTimers()
})
const notification = {
idempotencyKey: 'survey.assignment.created:assignment-1',
recipientUserId: 'ding-user-1',
title: '待填写',
content: '请完成考核调研',
actionTitle: '立即填写',
actionUrl: new URL('/performance-survey/survey/1', notifyOrigin).href,
}
test('使用项目签名提交通知任务', async () => {
const fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 202,
json: async () => ({
id: 'notification-1',
projectCode: 'test-project',
status: 'pending',
recipientUserId: 'ding-user-1',
title: '【由壹点·素材库】待填写',
}),
} as Response)
const result = await submitYouyidianNotification(notification)
expect(result.id).toBe('notification-1')
const [, init] = fetchMock.mock.calls[0]
expect(init?.headers).toMatchObject({
'x-yyd-project-code': 'test-project',
'x-yyd-signature': expect.stringMatching(/^[a-f0-9]{64}$/),
'x-yyd-nonce': expect.any(String),
})
})
test('读取通知回执正文超时时中止请求', async () => {
jest.useFakeTimers()
jest.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => ({
ok: true,
json: () => new Promise((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(init.signal?.reason), { once: true })
}),
}) as Response)
const rejected = expect(submitYouyidianNotification(notification)).rejects.toHaveProperty('name', 'AbortError')
await jest.advanceTimersByTimeAsync(8_000)
await rejected
})
})