import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { roleInterceptor } from './role.interceptor'; // currentRole() reads window.location.search; set it via the real URL rather than // vi.mock (the Angular unit-test system forbids mocking relative imports). beforeEach(() => window.history.replaceState({}, '', '/?role=admin')); afterEach(() => { window.history.replaceState({}, '', '/'); sessionStorage.clear(); // currentRole() now persists the dev role; don't leak across tests }); // Minimal stand-in for HttpRequest — the interceptor only reads `url` and calls // `clone({ setHeaders })`. Avoids importing @angular/common/http (its XHR chunk needs // the JIT compiler under vitest). function fakeReq(url: string) { const make = (headers: Map) => ({ url, headers, clone(opts: { setHeaders: Record }) { const next = new Map(headers); for (const [k, v] of Object.entries(opts.setHeaders)) next.set(k, v); return make(next); }, }); return make(new Map()); } /** Run the interceptor and return the request it forwarded to `next`. */ function forward(url: string) { let seen!: ReturnType; const next = (r: ReturnType) => { seen = r; return undefined; }; // Cast: the fake matches the shape the interceptor actually touches. (roleInterceptor as unknown as (req: unknown, next: unknown) => unknown)(fakeReq(url), next); return seen; } describe('roleInterceptor', () => { it.each([ '/api/v1/brief', '/api/v1/admin/org-template', '/api/v1/stamdata', // WP-29: the admin stamdata reads 403 without X-Role '/api/v1/stamdata/professions?peildatum=1999-01-01', '/api/v1/me', ])('stamps X-Role on the role-aware endpoint %s', (url) => { expect(forward(url).headers.get('X-Role')).toBe('admin'); }); it('leaves an unrelated endpoint untouched', () => { expect(forward('/api/v1/duo/diplomas').headers.has('X-Role')).toBe(false); }); });