Files
ApiCore/ApiCore-Backend/src/users/users.service.spec.ts
T
Nick SzaunigandClaude Sonnet 5 ae53f7889e feat: RBAC Phase 3 - LegacyRole-Enum, RolesGuard und @Roles vollstaendig entfernt
Letzte Phase des RBAC-Umbaus: die transitionale Rollen-Infrastruktur,
die seit Phase 1 parallel zum neuen Role/Permission-System mitlief,
ist jetzt komplett weg.

- Prisma-Migration: User.legacyRole-Spalte und LegacyRole-Enum
  gedroppt (nichts liest die Spalte mehr, seit Phase 2 jeder Controller
  auf @RequirePermission laeuft).
- roles.guard.ts, roles.guard.spec.ts, roles.decorator.ts geloescht;
  RolesGuard aus den APP_GUARD-Providern entfernt.
- AuthenticatedUser/JWT-Payload verlieren das role-Feld (permissions
  werden ohnehin frisch pro Request aus der DB aufgeloest, nicht aus
  dem Claim).
- Users-API: CreateUserDto/UpdateUserDto akzeptieren jetzt roleId
  (eine echte Role.id) statt der alten role-Enum-Werte; UsersService
  validiert, dass die Rolle existiert und aktiv ist, bevor sie
  zugewiesen wird.
- Alle 34 e2e-Fixtures und der Seed-Script folgen dem neuen Schema.

Verifiziert: tsc, lint, build, unit (220/220), volle e2e-Suite
159/159 gruen - keine uebersprungenen Tests.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-08-26 09:01:13 +02:00

199 lines
5.7 KiB
TypeScript

import { ConflictException, NotFoundException } from '@nestjs/common';
import { UsersService } from './users.service';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
describe('UsersService', () => {
let usersService: UsersService;
let prisma: {
user: {
findMany: jest.Mock;
findUnique: jest.Mock;
create: jest.Mock;
update: jest.Mock;
};
role: {
findUnique: jest.Mock;
};
};
let auditLog: { record: jest.Mock };
const staffRole = {
id: 'role-staff',
key: 'STAFF',
name: 'Mitarbeiter',
status: 'ACTIVE',
};
const existingUser = {
id: 'user-1',
email: '[email protected]',
passwordHash: 'hashed',
name: 'Existing User',
roleId: staffRole.id,
role: staffRole,
isActive: true,
createdAt: new Date(),
deactivatedAt: null,
};
beforeEach(() => {
prisma = {
user: {
findMany: jest.fn(),
findUnique: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
role: {
findUnique: jest.fn().mockResolvedValue(staffRole),
},
};
auditLog = { record: jest.fn().mockResolvedValue(undefined) };
usersService = new UsersService(
prisma as unknown as PrismaService,
auditLog as unknown as AuditLogService,
);
});
it('findAll returns summaries without the password hash', async () => {
prisma.user.findMany.mockResolvedValue([existingUser]);
const result = await usersService.findAll();
expect(result).toEqual([
{
id: existingUser.id,
email: existingUser.email,
name: existingUser.name,
roleId: staffRole.id,
roleKey: staffRole.key,
roleName: staffRole.name,
isActive: existingUser.isActive,
createdAt: existingUser.createdAt,
deactivatedAt: existingUser.deactivatedAt,
},
]);
expect(result[0]).not.toHaveProperty('passwordHash');
});
it('findById throws NotFoundException when the user is missing', async () => {
prisma.user.findUnique.mockResolvedValue(null);
await expect(usersService.findById('missing')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('create throws ConflictException when the email is already in use', async () => {
prisma.user.findUnique.mockResolvedValue(existingUser);
await expect(
usersService.create({
email: existingUser.email,
password: 'password123',
name: 'New',
roleId: staffRole.id,
}),
).rejects.toBeInstanceOf(ConflictException);
});
it('create throws NotFoundException when the role does not exist', async () => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.role.findUnique.mockResolvedValue(null);
await expect(
usersService.create({
email: '[email protected]',
password: 'password123',
name: 'New User',
roleId: 'missing-role',
}),
).rejects.toBeInstanceOf(NotFoundException);
});
it('create throws ConflictException when the role is not active', async () => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.role.findUnique.mockResolvedValue({
...staffRole,
status: 'INACTIVE',
});
await expect(
usersService.create({
email: '[email protected]',
password: 'password123',
name: 'New User',
roleId: staffRole.id,
}),
).rejects.toBeInstanceOf(ConflictException);
});
it('create hashes the password, persists the user, and records an audit entry', async () => {
prisma.user.findUnique.mockResolvedValue(null);
prisma.user.create.mockResolvedValue({
...existingUser,
id: 'user-2',
email: '[email protected]',
});
const result = await usersService.create({
email: '[email protected]',
password: 'password123',
name: 'New User',
roleId: staffRole.id,
});
expect(result.id).toBe('user-2');
const [[createArg]] = prisma.user.create.mock.calls as [
[{ data: { email: string; passwordHash: string } }],
];
expect(createArg.data.email).toBe('[email protected]');
expect(createArg.data.passwordHash).not.toBe('password123');
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({ entityType: 'User', action: 'CREATE' }),
);
});
it('deactivate sets isActive to false and records an audit entry', async () => {
prisma.user.findUnique.mockResolvedValue(existingUser);
prisma.user.update.mockResolvedValue({
...existingUser,
isActive: false,
deactivatedAt: new Date(),
});
const result = await usersService.deactivate(existingUser.id);
expect(result.isActive).toBe(false);
expect(result.deactivatedAt).not.toBeNull();
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({ entityType: 'User', action: 'DEACTIVATE' }),
);
});
it('activate throws ConflictException when already active', async () => {
prisma.user.findUnique.mockResolvedValue(existingUser);
await expect(usersService.activate(existingUser.id)).rejects.toBeInstanceOf(
ConflictException,
);
});
it('activate sets isActive to true and clears deactivatedAt', async () => {
prisma.user.findUnique.mockResolvedValue({
...existingUser,
isActive: false,
deactivatedAt: new Date(),
});
prisma.user.update.mockResolvedValue({
...existingUser,
isActive: true,
deactivatedAt: null,
});
const result = await usersService.activate(existingUser.id);
expect(result.isActive).toBe(true);
expect(result.deactivatedAt).toBeNull();
expect(auditLog.record).toHaveBeenCalledWith(
expect.objectContaining({ entityType: 'User', action: 'UPDATE' }),
);
});
});