adds unit tests to cover 80%

This commit is contained in:
2026-06-26 00:27:27 +02:00
parent b84e2f8e3e
commit 0e01ca1e1c
69 changed files with 90596 additions and 46 deletions
+186
View File
@@ -0,0 +1,186 @@
import { describe, expect, it, vi } from 'vitest';
import { http, HttpResponse } from 'msw';
import { server } from '@/mocks/server';
import { ApiClient, ProblemDetailsError, NetworkError } from '@/lib/api-client';
const BASE = 'http://localhost:5000';
function makeClient() {
return new ApiClient(BASE);
}
describe('ApiClient', () => {
it('makes a GET request and parses JSON response', async () => {
server.use(http.get(`${BASE}/test`, () => HttpResponse.json({ ok: true })));
const client = makeClient();
const result = await client.get<{ ok: boolean }>('/test');
expect(result).toEqual({ ok: true });
});
it('makes a POST request with JSON body', async () => {
server.use(
http.post(`${BASE}/test`, async ({ request }) => {
const body = (await request.json()) as { name: string };
return HttpResponse.json({ received: body.name });
}),
);
const client = makeClient();
const result = await client.post<{ received: string }>('/test', { name: 'hello' });
expect(result.received).toBe('hello');
});
it('makes a PUT request', async () => {
server.use(http.put(`${BASE}/item/1`, () => HttpResponse.json({ updated: true })));
const client = makeClient();
const result = await client.put<{ updated: boolean }>('/item/1', { value: 'x' });
expect(result.updated).toBe(true);
});
it('returns undefined for 204 No Content responses', async () => {
server.use(http.delete(`${BASE}/item/1`, () => new HttpResponse(null, { status: 204 })));
const client = makeClient();
const result = await client.delete<undefined>('/item/1');
expect(result).toBeUndefined();
});
it('throws ProblemDetailsError on non-2xx response', async () => {
server.use(
http.get(`${BASE}/notfound`, () =>
HttpResponse.json({ title: 'Not Found', status: 404 }, { status: 404 }),
),
);
const client = makeClient();
await expect(client.get('/notfound')).rejects.toThrow(ProblemDetailsError);
});
it('ProblemDetailsError carries status and problem details', async () => {
server.use(
http.get(`${BASE}/bad`, () =>
HttpResponse.json({ title: 'Bad Request', status: 400, detail: 'Invalid input' }, { status: 400 }),
),
);
const client = makeClient();
try {
await client.get('/bad');
expect.fail('should have thrown');
} catch (err) {
expect(err).toBeInstanceOf(ProblemDetailsError);
const pde = err as ProblemDetailsError;
expect(pde.status).toBe(400);
expect(pde.problem.title).toBe('Bad Request');
}
});
it('injects Bearer token when access token is set', async () => {
let capturedAuth: string | null = null;
server.use(
http.get(`${BASE}/secured`, ({ request }) => {
capturedAuth = request.headers.get('Authorization');
return HttpResponse.json({});
}),
);
const client = makeClient();
client.setAccessToken('my-token');
await client.get('/secured');
expect(capturedAuth).toBe('Bearer my-token');
});
it('does not inject auth header when no access token is set', async () => {
let capturedAuth: string | null = null;
server.use(
http.get(`${BASE}/public`, ({ request }) => {
capturedAuth = request.headers.get('Authorization');
return HttpResponse.json({});
}),
);
const client = makeClient();
await client.get('/public');
expect(capturedAuth).toBeNull();
});
it('clears token when setAccessToken(null) is called', async () => {
let capturedAuth: string | null = null;
server.use(
http.get(`${BASE}/cleared`, ({ request }) => {
capturedAuth = request.headers.get('Authorization');
return HttpResponse.json({});
}),
);
const client = makeClient();
client.setAccessToken('my-token');
client.setAccessToken(null);
await client.get('/cleared');
expect(capturedAuth).toBeNull();
});
it('retries once with new token after 401', async () => {
let callCount = 0;
server.use(
http.get(`${BASE}/protected`, () => {
callCount += 1;
if (callCount === 1) return new HttpResponse(null, { status: 401 });
return HttpResponse.json({ secret: 'data' });
}),
);
const client = makeClient();
client.setRefreshHandler(async () => 'new-token');
const result = await client.get<{ secret: string }>('/protected');
expect(result.secret).toBe('data');
expect(callCount).toBe(2);
});
it('calls authFailureHandler and throws when refresh returns null', async () => {
server.use(http.get(`${BASE}/protected`, () => new HttpResponse(null, { status: 401 })));
const client = makeClient();
const failureFn = vi.fn();
client.setRefreshHandler(async () => null);
client.setAuthFailureHandler(failureFn);
await expect(client.get('/protected')).rejects.toThrow(ProblemDetailsError);
expect(failureFn).toHaveBeenCalledOnce();
});
it('does not retry 401 when skipAuthRefresh is set', async () => {
let callCount = 0;
server.use(
http.get(`${BASE}/skip`, () => {
callCount += 1;
return new HttpResponse(null, { status: 401 });
}),
);
const client = makeClient();
client.setRefreshHandler(async () => 'new-token');
await expect(
client.get('/skip', { skipAuthRefresh: true }),
).rejects.toThrow(ProblemDetailsError);
expect(callCount).toBe(1);
});
it('throws NetworkError when fetch fails', async () => {
server.use(http.get(`${BASE}/network-fail`, () => HttpResponse.error()));
const client = makeClient();
await expect(client.get('/network-fail')).rejects.toThrow(NetworkError);
});
});
+122
View File
@@ -0,0 +1,122 @@
import { describe, expect, it } from 'vitest';
import {
passwordSchema,
setupFormSchema,
loginFormSchema,
invitationCompleteFormSchema,
} from '@/lib/schemas/auth';
describe('passwordSchema', () => {
it('accepts a valid password', () => {
expect(passwordSchema.safeParse('Password1!').success).toBe(true);
});
it('rejects a password that is too short', () => {
expect(passwordSchema.safeParse('Pass1!').success).toBe(false);
});
it('rejects a password without an uppercase letter', () => {
expect(passwordSchema.safeParse('password1!').success).toBe(false);
});
it('rejects a password without a digit', () => {
expect(passwordSchema.safeParse('Password!').success).toBe(false);
});
it('rejects a password without a special character', () => {
expect(passwordSchema.safeParse('Password1').success).toBe(false);
});
});
describe('setupFormSchema', () => {
const valid = {
name: 'Admin',
email: 'admin@example.com',
password: 'Password1!',
confirmPassword: 'Password1!',
language: 'nl' as const,
};
it('accepts valid setup data', () => {
expect(setupFormSchema.safeParse(valid).success).toBe(true);
});
it('rejects when passwords do not match', () => {
const result = setupFormSchema.safeParse({ ...valid, confirmPassword: 'Different1!' });
expect(result.success).toBe(false);
});
it('rejects empty name', () => {
expect(setupFormSchema.safeParse({ ...valid, name: '' }).success).toBe(false);
});
it('rejects name exceeding 255 characters', () => {
expect(setupFormSchema.safeParse({ ...valid, name: 'a'.repeat(256) }).success).toBe(false);
});
it('rejects invalid email format', () => {
expect(setupFormSchema.safeParse({ ...valid, email: 'not-an-email' }).success).toBe(false);
});
it('rejects empty email', () => {
expect(setupFormSchema.safeParse({ ...valid, email: '' }).success).toBe(false);
});
it('rejects invalid language', () => {
expect(setupFormSchema.safeParse({ ...valid, language: 'fr' }).success).toBe(false);
});
it('accepts "en" as language', () => {
expect(setupFormSchema.safeParse({ ...valid, language: 'en' }).success).toBe(true);
});
});
describe('loginFormSchema', () => {
it('accepts valid login credentials', () => {
expect(loginFormSchema.safeParse({ email: 'user@example.com', password: 'anypass' }).success).toBe(true);
});
it('rejects empty email', () => {
expect(loginFormSchema.safeParse({ email: '', password: 'pass' }).success).toBe(false);
});
it('rejects invalid email format', () => {
expect(loginFormSchema.safeParse({ email: 'not-email', password: 'pass' }).success).toBe(false);
});
it('rejects empty password', () => {
expect(loginFormSchema.safeParse({ email: 'user@example.com', password: '' }).success).toBe(false);
});
});
describe('invitationCompleteFormSchema', () => {
const valid = {
name: 'New User',
password: 'Password1!',
confirmPassword: 'Password1!',
};
it('accepts valid invitation completion data', () => {
expect(invitationCompleteFormSchema.safeParse(valid).success).toBe(true);
});
it('rejects when passwords do not match', () => {
expect(
invitationCompleteFormSchema.safeParse({ ...valid, confirmPassword: 'Different1!' }).success,
).toBe(false);
});
it('rejects empty name', () => {
expect(invitationCompleteFormSchema.safeParse({ ...valid, name: '' }).success).toBe(false);
});
it('rejects weak password', () => {
expect(
invitationCompleteFormSchema.safeParse({
...valid,
password: 'weak',
confirmPassword: 'weak',
}).success,
).toBe(false);
});
});