gongxiangp2/lib/__tests__/users-list-route.test.ts
2026-07-30 14:39:30 +08:00

90 lines
2.0 KiB
TypeScript

/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { GET } from '@/app/api/users/list/route'
import { prisma } from '@/lib/prisma'
jest.mock('next-auth', () => ({
getServerSession: jest.fn(),
}))
jest.mock('@/lib/auth', () => ({
authOptions: {},
}))
jest.mock('@/lib/prisma', () => ({
prisma: {
user: {
findMany: jest.fn(),
},
},
}))
describe('GET /api/users/list', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test('未登录时返回 401 且不读取人员数据', async () => {
;(getServerSession as jest.Mock).mockResolvedValue(null)
const response = await GET(new NextRequest('http://localhost/api/users/list'))
expect(response.status).toBe(401)
expect(prisma.user.findMany).not.toHaveBeenCalled()
})
test('只读取并返回人员选择器需要的最小字段', async () => {
;(getServerSession as jest.Mock).mockResolvedValue({
user: { id: 'user-1' },
})
;(prisma.user.findMany as jest.Mock).mockResolvedValue([
{
id: 'user-1',
username: 'moli',
realName: '魔礼红',
},
{
id: 'user-2',
username: 'wuxie',
realName: null,
},
])
const response = await GET(new NextRequest('http://localhost/api/users/list'))
const body = await response.json()
expect(response.status).toBe(200)
expect(prisma.user.findMany).toHaveBeenCalledWith({
where: {
isActive: true,
status: 'active',
archivedAt: null,
},
select: {
id: true,
username: true,
realName: true,
},
orderBy: {
username: 'asc',
},
})
expect(body).toEqual([
{
id: 'user-1',
username: 'moli',
displayName: '魔礼红',
},
{
id: 'user-2',
username: 'wuxie',
displayName: 'wuxie',
},
])
expect(body[0]).not.toHaveProperty('email')
expect(body[0]).not.toHaveProperty('realName')
})
})