gongxiangp2/lib/__tests__/department-permission-source.test.ts
2026-05-14 14:58:12 +08:00

75 lines
2.2 KiB
TypeScript

/** @jest-environment node */
import { canUserDownloadSource } from '@/lib/department-permission'
import { prisma } from '@/lib/prisma'
jest.mock('@/lib/prisma', () => ({
prisma: {
user: {
findUnique: jest.fn(),
},
department: {
findMany: jest.fn(),
},
departmentMaterialPermission: {
findUnique: jest.fn(),
},
},
}))
const departments = [
{ id: 'visual-center', name: '视觉中心', parentId: null },
{ id: 'visual-third', name: '视觉三部', parentId: 'visual-center' },
]
function mockPermissionLookup(records: Record<string, { canDownloadSource: boolean }>) {
;(prisma.departmentMaterialPermission.findUnique as jest.Mock).mockImplementation(
async ({ where }: any) => {
const key = `${where.department_materialType.department}:${where.department_materialType.materialType}`
const record = records[key]
if (!record) {
return null
}
return {
department: where.department_materialType.department,
materialType: where.department_materialType.materialType,
canView: true,
canDownload: true,
canShare: true,
canDownloadSource: record.canDownloadSource,
linkedToDepartment: null,
}
},
)
}
describe('canUserDownloadSource', () => {
beforeEach(() => {
jest.clearAllMocks()
;(prisma.user.findUnique as jest.Mock).mockResolvedValue({ isSuperAdmin: false })
;(prisma.department.findMany as jest.Mock).mockResolvedValue(departments)
})
test('子部门没有独立配置时继承父部门源文件下载权限', async () => {
mockPermissionLookup({
'视觉中心:详情模板': { canDownloadSource: true },
})
await expect(
canUserDownloadSource('视觉三部', 'USER', null, '详情模板', 'user-1'),
).resolves.toBe(true)
})
test('子部门独立配置优先于父部门源文件下载权限', async () => {
mockPermissionLookup({
'视觉中心:详情模板': { canDownloadSource: true },
'视觉三部:详情模板': { canDownloadSource: false },
})
await expect(
canUserDownloadSource('视觉三部', 'USER', null, '详情模板', 'user-1'),
).resolves.toBe(false)
})
})