61 lines
4.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { prisma } from '@/lib/prisma'
import { GET, POST } from './route'
import { PUT, DELETE } from './[id]/route'
import { GET as SOURCES } from './sources/route'
import { GET as EXPORT } from './export/route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { user: { findUnique: jest.fn() }, personnelSalaryBase: { findMany: jest.fn() }, salaryPositionConfig: { findMany: jest.fn() }, performanceSurveyTemplate: { findMany: jest.fn() }, $transaction: jest.fn() } }))
const session = getServerSession as jest.Mock, user = prisma.user.findUnique as jest.Mock
const req = (method: string, body: unknown = {}, headers: Record<string, string> = {}) => new NextRequest('http://localhost/api/organization/performance-salary/positions', { method, body: JSON.stringify(body), headers })
const all = () => [GET(new NextRequest('http://localhost/api/organization/performance-salary/positions')), POST(req('POST')), PUT(req('PUT'), { params: { id: 'id' } }), DELETE(req('DELETE'), { params: { id: 'id' } }), SOURCES(), EXPORT(new NextRequest('http://localhost/api/organization/performance-salary/positions/export'))]
beforeEach(() => {
jest.resetAllMocks()
;(prisma.personnelSalaryBase.findMany as jest.Mock).mockResolvedValue([])
session.mockResolvedValue({ user: { id: 'old-admin', isSuperAdmin: true } })
user.mockResolvedValue({ id: 'old-admin', isSuperAdmin: false, isActive: true, status: 'active', archivedAt: null })
})
test('全部新接口独立拒绝旧超管会话且禁止缓存', async () => {
for (const response of await Promise.all(all())) {
expect(response.status).toBe(403)
expect(response.headers.get('cache-control')).toBe('private, no-store, max-age=0')
}
expect(prisma.$transaction).not.toHaveBeenCalled()
expect(prisma.salaryPositionConfig.findMany).not.toHaveBeenCalled()
})
test('未登录全部拒绝', async () => {
session.mockResolvedValue(null)
for (const response of await Promise.all(all())) expect(response.status).toBe(401)
})
test.each(['c156778c-307d-42aa-89d3-f785aeb3ef86', '463c5a60-c8a8-45dd-b4cd-4a31a6b1b84f', 'c041d8d8-93db-41f1-984d-5f76f114da48', '2b1ccc12-844c-4eff-8006-58607157efc1'])('指定账号%s仅可读和导出', async id => {
session.mockResolvedValue({ user: { id, isSuperAdmin: true } })
user.mockResolvedValue({ id, isSuperAdmin: false, isActive: true, status: 'active', archivedAt: null })
;(prisma.salaryPositionConfig.findMany as jest.Mock).mockResolvedValue([{ id: 'job', name: '空岗位', salaryRole: 'ai-planning', description: '', dimensions: [], revision: 1, updatedAt: new Date(), _count: { people: 7 } }])
;(prisma.performanceSurveyTemplate.findMany as jest.Mock).mockResolvedValue([])
const responses = await Promise.all(all())
expect(responses.map(r => r.status)).toEqual([200, 403, 403, 403, 200, 200])
expect(responses[5].headers.get('content-type')).toContain('spreadsheetml')
expect(responses[5].headers.get('cache-control')).toContain('no-store')
})
test('跨站写拒绝;错误权重不进事务', async () => {
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
expect((await POST(req('POST', {}, { origin: 'https://other.test' }))).status).toBe(403)
expect((await POST(req('POST', { name: '', dimensions: [] }))).status).toBe(400)
expect(prisma.$transaction).not.toHaveBeenCalled()
})
test.each(['same-origin', 'cross-site'])('代理后岗位新增、编辑、删除按%s来源校验,拒绝时不写库', async site => {
user.mockResolvedValue({ id: 'admin', isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true })
const proxied = (method: string) => new NextRequest('https://0.0.0.0:3000/api/organization/performance-salary/positions', {
method, headers: { origin: 'https://sc.jiansun.vip', host: 'sc.jiansun.vip', 'x-forwarded-proto': 'https', 'sec-fetch-site': site }, body: '{}',
})
const responses = await Promise.all([POST(proxied('POST')), PUT(proxied('PUT'), { params: { id: 'id' } }), DELETE(proxied('DELETE'), { params: { id: 'id' } })])
for (const response of responses) {
expect(response.status).toBe(site === 'same-origin' ? 400 : 403)
expect(response.headers.get('cache-control')).toBe('private, no-store, max-age=0')
}
expect(prisma.$transaction).not.toHaveBeenCalled()
})