Files
FitOS/app/test/auth-store.test.ts
2026-09-04 19:06:19 +02:00

119 lines
3.8 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { useAuth } from '../src/store/auth';
import { setAccessToken, getAccessToken } from '../src/api/client';
import type { User } from '../src/api/types';
const USER: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
age: 30,
heightCm: 180,
phone: null,
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-22T10:00:00.000Z',
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function mockFetchSequence(...responses: Response[]) {
const fetchMock = vi.fn(async (url: string) => {
const next = responses.shift();
if (!next) throw new Error(`No more mocked responses for url: ${url}`);
return next;
});
vi.stubGlobal('fetch', fetchMock);
return fetchMock;
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('auth store', () => {
it('login stores the user and the access token', async () => {
mockFetchSequence(jsonResponse(200, { user: USER, accessToken: 'tok-1' }));
await useAuth.getState().login('jan@test.local', 'Password123!');
expect(useAuth.getState().user).toEqual(USER);
expect(getAccessToken()).toBe('tok-1');
expect(localStorage.getItem('fitos_access')).toBe('tok-1');
});
it('login rejects on invalid credentials and keeps the user null', async () => {
mockFetchSequence(
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Invalid credentials' } }),
);
await expect(useAuth.getState().login('jan@test.local', 'wrong')).rejects.toThrow(
'Invalid credentials',
);
expect(useAuth.getState().user).toBeNull();
expect(getAccessToken()).toBeNull();
});
it('register stores the user and the access token', async () => {
mockFetchSequence(jsonResponse(201, { user: USER, accessToken: 'tok-2' }));
await useAuth.getState().register({ email: 'jan@test.local', password: 'Password123!' });
expect(useAuth.getState().user).toEqual(USER);
expect(getAccessToken()).toBe('tok-2');
});
it('logout clears the user and the token even when the API call fails', async () => {
useAuth.setState({ user: USER });
setAccessToken('tok-3');
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('', { status: 500 })),
);
await useAuth.getState().logout();
expect(useAuth.getState().user).toBeNull();
expect(getAccessToken()).toBeNull();
});
it('init restores the session via refresh + /me', async () => {
const fetchMock = mockFetchSequence(
jsonResponse(200, { accessToken: 'tok-4' }),
jsonResponse(200, { user: USER }),
);
await useAuth.getState().init();
expect(useAuth.getState().user).toEqual(USER);
expect(useAuth.getState().ready).toBe(true);
expect(getAccessToken()).toBe('tok-4');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('init without a valid session ends with a null user and ready=true', async () => {
mockFetchSequence(
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Invalid refresh token' } }),
);
await useAuth.getState().init();
expect(useAuth.getState().user).toBeNull();
expect(useAuth.getState().ready).toBe(true);
});
it('the fitos:logout event clears the user', () => {
useAuth.setState({ user: USER });
window.dispatchEvent(new Event('fitos:logout'));
expect(useAuth.getState().user).toBeNull();
});
});