102 lines
2.6 KiB
TypeScript
102 lines
2.6 KiB
TypeScript
jest.mock('@/lib/auth', () => ({
|
|
authOptions: {},
|
|
}))
|
|
|
|
jest.mock('next-auth', () => ({
|
|
getServerSession: jest.fn(),
|
|
}))
|
|
|
|
jest.mock('@/lib/prisma', () => ({
|
|
prisma: {
|
|
user: {
|
|
findUnique: jest.fn(),
|
|
update: jest.fn(),
|
|
},
|
|
$transaction: jest.fn(),
|
|
},
|
|
}))
|
|
|
|
jest.mock('bcryptjs', () => ({
|
|
compare: jest.fn(),
|
|
}))
|
|
|
|
import { NextRequest } from 'next/server'
|
|
import { POST } from '../route'
|
|
|
|
const { getServerSession } = require('next-auth')
|
|
const { prisma } = require('@/lib/prisma')
|
|
const bcrypt = require('bcryptjs')
|
|
|
|
function createTransferRequest(body: Record<string, unknown>) {
|
|
return new NextRequest('http://localhost/api/admin/transfer-superadmin', {
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
}
|
|
|
|
describe('POST /api/admin/transfer-superadmin', () => {
|
|
beforeEach(() => {
|
|
jest.resetAllMocks()
|
|
getServerSession.mockResolvedValue({
|
|
user: { id: 'super-1', role: 'ADMIN', isSuperAdmin: true },
|
|
})
|
|
bcrypt.compare.mockResolvedValue(true)
|
|
prisma.$transaction.mockResolvedValue([])
|
|
})
|
|
|
|
it('禁用的最高权限账号不能转移最高权限', async () => {
|
|
prisma.user.findUnique.mockResolvedValueOnce({
|
|
id: 'super-1',
|
|
isSuperAdmin: true,
|
|
isActive: false,
|
|
password: 'hashed-password',
|
|
})
|
|
|
|
const response = await POST(createTransferRequest({
|
|
targetUserId: 'user-2',
|
|
password: 'right-password',
|
|
}))
|
|
const data = await response.json()
|
|
|
|
expect(response.status).toBe(403)
|
|
expect(data.error).toBe('仅最高权限账号可转移最高权限')
|
|
expect(bcrypt.compare).not.toHaveBeenCalled()
|
|
expect(prisma.user.update).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('转移最高权限时会把目标账号修正为可登录管理员', async () => {
|
|
prisma.user.findUnique
|
|
.mockResolvedValueOnce({
|
|
id: 'super-1',
|
|
isSuperAdmin: true,
|
|
isActive: true,
|
|
password: 'hashed-password',
|
|
})
|
|
.mockResolvedValueOnce({
|
|
id: 'user-2',
|
|
email: 'user2@example.com',
|
|
role: 'USER',
|
|
isActive: false,
|
|
})
|
|
prisma.user.update.mockResolvedValue({})
|
|
|
|
const response = await POST(createTransferRequest({
|
|
targetUserId: 'user-2',
|
|
password: 'right-password',
|
|
}))
|
|
const data = await response.json()
|
|
|
|
expect(response.status).toBe(200)
|
|
expect(data.message).toBe('最高权限已转移')
|
|
expect(prisma.user.update).toHaveBeenCalledWith({
|
|
where: { id: 'user-2' },
|
|
data: {
|
|
isSuperAdmin: true,
|
|
role: 'ADMIN',
|
|
isActive: true,
|
|
},
|
|
})
|
|
})
|
|
})
|