89 lines
2.4 KiB
TypeScript
89 lines
2.4 KiB
TypeScript
import { NextRequest } from 'next/server'
|
|
import { POST } from '../route'
|
|
|
|
jest.mock('@/lib/prisma', () => ({
|
|
prisma: {
|
|
systemSettings: {
|
|
findFirst: jest.fn(),
|
|
},
|
|
invitation: {
|
|
findUnique: jest.fn(),
|
|
},
|
|
user: {
|
|
findFirst: jest.fn(),
|
|
},
|
|
$transaction: jest.fn(),
|
|
},
|
|
}))
|
|
|
|
jest.mock('@/lib/license', () => ({
|
|
canCreateUser: jest.fn(),
|
|
}))
|
|
|
|
jest.mock('bcryptjs', () => ({
|
|
hash: jest.fn(async (value: string) => `hashed:${value}`),
|
|
}))
|
|
|
|
const { prisma } = require('@/lib/prisma')
|
|
const { canCreateUser } = require('@/lib/license')
|
|
const bcrypt = require('bcryptjs')
|
|
|
|
function createRequest(body: Record<string, unknown>) {
|
|
return new NextRequest('http://localhost/api/auth/register', {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
email: 'user@example.com',
|
|
username: 'user',
|
|
department: '默认部门',
|
|
password: 'Flnxi-2026-Safe',
|
|
...body,
|
|
}),
|
|
})
|
|
}
|
|
|
|
describe('POST /api/auth/register', () => {
|
|
beforeEach(() => {
|
|
jest.resetAllMocks()
|
|
canCreateUser.mockResolvedValue({ allowed: true })
|
|
prisma.systemSettings.findFirst.mockResolvedValue({ enableRegistration: true })
|
|
prisma.user.findFirst.mockResolvedValue(null)
|
|
prisma.$transaction.mockImplementation(async (callback: any) => callback({
|
|
user: {
|
|
count: jest.fn().mockResolvedValue(1),
|
|
findFirst: jest.fn().mockResolvedValue(null),
|
|
create: jest.fn().mockResolvedValue({
|
|
id: 'user-1',
|
|
email: 'user@example.com',
|
|
username: 'user',
|
|
department: '默认部门',
|
|
role: 'USER',
|
|
createdAt: new Date('2026-05-25T00:00:00.000Z'),
|
|
}),
|
|
},
|
|
invitation: {
|
|
update: jest.fn(),
|
|
},
|
|
}))
|
|
})
|
|
|
|
test('注册时拒绝弱密码', async () => {
|
|
const response = await POST(createRequest({ password: '123456' }))
|
|
const data = await response.json()
|
|
|
|
expect(response.status).toBe(400)
|
|
expect(data.error).toContain('至少')
|
|
expect(prisma.user.findFirst).not.toHaveBeenCalled()
|
|
expect(bcrypt.hash).not.toHaveBeenCalled()
|
|
expect(prisma.$transaction).not.toHaveBeenCalled()
|
|
})
|
|
|
|
test('强密码注册仍可成功', async () => {
|
|
const response = await POST(createRequest({ password: 'Flnxi-2026-Safe' }))
|
|
const data = await response.json()
|
|
|
|
expect(response.status).toBe(201)
|
|
expect(data.message).toBe('注册成功')
|
|
expect(bcrypt.hash).toHaveBeenCalledWith('Flnxi-2026-Safe', 10)
|
|
})
|
|
})
|