Refactor useAuth hooks for improved type safety, error handling, and compliance with auto-generated API client

- Migrated `useAuth` hooks to use functions from auto-generated API client for improved maintainability and OpenAPI compliance.
- Replaced manual API calls with SDK functions (`login`, `register`, `logout`, etc.) and added error type guards for runtime safety (`isTokenWithUser`, `isSuccessResponse`).
- Enhanced hooks with better error logging, optional success callbacks, and stricter type annotations.
- Refactored `Logout` and `LogoutAll` mutations to handle missing tokens gracefully and clear local state on server failure.
- Added tests for API type guards and updated functionality of hooks to validate proper behaviors.
- Removed legacy `client-config.ts` to align with new API client utilization.
- Improved inline documentation for hooks with detailed descriptions and usage guidance.
This commit is contained in:
Felipe Cardoso
2025-11-01 04:25:44 +01:00
parent 3ad48843e4
commit ea544ecbac
12 changed files with 2212 additions and 282 deletions

View File

@@ -0,0 +1,499 @@
/**
* Comprehensive tests for API client wrapper with interceptors
*
* Tests cover:
* - Client configuration
* - Request interceptor (Authorization header injection)
* - Response interceptor (error handling)
* - Token refresh mechanism
* - Token refresh singleton pattern (race condition prevention)
* - All HTTP error status codes (401, 403, 404, 429, 500+)
* - Network errors
* - Edge cases and error recovery
*/
import MockAdapter from 'axios-mock-adapter';
import { apiClient } from '@/lib/api/client';
import config from '@/config/app.config';
// Mock auth store
let mockAuthStore = {
accessToken: null as string | null,
refreshToken: null as string | null,
setTokens: jest.fn(),
clearAuth: jest.fn(),
};
// Mock the auth store module
jest.mock('@/stores/authStore', () => ({
useAuthStore: {
getState: () => mockAuthStore,
},
}));
// Create mock adapter
let mock: MockAdapter;
describe('API Client Wrapper', () => {
beforeEach(() => {
// Reset mock auth store
mockAuthStore = {
accessToken: null,
refreshToken: null,
setTokens: jest.fn(),
clearAuth: jest.fn(),
};
// Reset mocks
jest.clearAllMocks();
// Create new mock adapter for each test (fresh state)
mock = new MockAdapter(apiClient.instance);
});
afterEach(() => {
// Reset the mock adapter
mock.reset();
mock.restore();
});
describe('Client Configuration', () => {
it('should have correct base URL from config', () => {
expect(apiClient.instance.defaults.baseURL).toBe(config.api.url);
});
it('should have correct timeout from config', () => {
expect(apiClient.instance.defaults.timeout).toBe(config.api.timeout);
});
it('should have correct Content-Type header', () => {
expect(apiClient.instance.defaults.headers['Content-Type']).toBe('application/json');
});
});
describe('Request Interceptor - Authorization Header', () => {
it('should add Authorization header when access token exists', async () => {
mockAuthStore.accessToken = 'test-access-token';
mock.onGet('/api/v1/test').reply((config) => {
expect(config.headers?.Authorization).toBe('Bearer test-access-token');
return [200, { success: true }];
});
await apiClient.instance.get('/api/v1/test');
});
it('should not add Authorization header when no access token', async () => {
mockAuthStore.accessToken = null;
mock.onGet('/api/v1/test').reply((config) => {
expect(config.headers?.Authorization).toBeUndefined();
return [200, { success: true }];
});
await apiClient.instance.get('/api/v1/test');
});
it('should update Authorization header if token changes', async () => {
// First request with old token
mockAuthStore.accessToken = 'old-token';
mock.onGet('/api/v1/test1').reply((config) => {
expect(config.headers?.Authorization).toBe('Bearer old-token');
return [200, { success: true }];
});
await apiClient.instance.get('/api/v1/test1');
// Change token
mockAuthStore.accessToken = 'new-token';
mock.onGet('/api/v1/test2').reply((config) => {
expect(config.headers?.Authorization).toBe('Bearer new-token');
return [200, { success: true }];
});
await apiClient.instance.get('/api/v1/test2');
});
});
describe('Response Interceptor - 401 Unauthorized with Token Refresh', () => {
it('should refresh token and retry request on 401', async () => {
mockAuthStore.accessToken = 'expired-token';
mockAuthStore.refreshToken = 'valid-refresh-token';
let requestCount = 0;
// Protected endpoint that fails first time, succeeds after refresh
mock.onGet('/api/v1/protected').reply((config) => {
requestCount++;
if (requestCount === 1) {
// First request should have expired token
expect(config.headers?.Authorization).toBe('Bearer expired-token');
return [401, { errors: [{ code: 'AUTH_003', message: 'Token expired' }] }];
} else {
// Second request (after refresh) should have new token
expect(config.headers?.Authorization).toBe('Bearer new-access-token');
return [200, { data: 'protected data' }];
}
});
// Mock the refresh endpoint
mock.onPost('/api/v1/auth/refresh').reply(200, {
access_token: 'new-access-token',
refresh_token: 'new-refresh-token',
token_type: 'bearer',
});
// Make the request
const response = await apiClient.instance.get('/api/v1/protected');
expect(requestCount).toBe(2); // Original + retry
expect(response.data).toEqual({ data: 'protected data' });
expect(mockAuthStore.setTokens).toHaveBeenCalledWith(
'new-access-token',
'new-refresh-token',
undefined
);
});
it('should not retry if request was to refresh endpoint', async () => {
mockAuthStore.accessToken = 'expired-token';
mockAuthStore.refreshToken = 'expired-refresh-token';
mock.onPost('/api/v1/auth/refresh').reply(401, {
errors: [{ code: 'AUTH_003', message: 'Refresh token expired' }],
});
await expect(
apiClient.instance.post('/api/v1/auth/refresh', {
refresh_token: 'expired-refresh-token',
})
).rejects.toThrow();
// Should clear auth
expect(mockAuthStore.clearAuth).toHaveBeenCalled();
});
it('should clear auth and redirect on refresh failure', async () => {
mockAuthStore.accessToken = 'expired-token';
mockAuthStore.refreshToken = 'expired-refresh-token';
// Mock window.location
delete (global as any).window;
(global as any).window = {
location: { href: '', pathname: '/dashboard' },
};
mock.onGet('/api/v1/protected').reply(401, {
errors: [{ code: 'AUTH_003', message: 'Token expired' }],
});
mock.onPost('/api/v1/auth/refresh').reply(401, {
errors: [{ code: 'AUTH_003', message: 'Refresh token expired' }],
});
await expect(
apiClient.instance.get('/api/v1/protected')
).rejects.toThrow();
expect(mockAuthStore.clearAuth).toHaveBeenCalled();
expect(window.location.href).toContain('/login');
expect(window.location.href).toContain('returnUrl=/dashboard');
});
it('should not add returnUrl for login and register pages', async () => {
mockAuthStore.accessToken = 'expired-token';
mockAuthStore.refreshToken = 'expired-refresh-token';
// Mock window.location for login page
delete (global as any).window;
(global as any).window = {
location: { href: '', pathname: '/login' },
};
mock.onGet('/api/v1/protected').reply(401);
mock.onPost('/api/v1/auth/refresh').reply(401);
await expect(
apiClient.instance.get('/api/v1/protected')
).rejects.toThrow();
expect(window.location.href).toBe('/login');
expect(window.location.href).not.toContain('returnUrl');
});
});
describe('Response Interceptor - 403 Forbidden', () => {
it('should pass through 403 errors without retry', async () => {
mockAuthStore.accessToken = 'valid-token';
mock.onGet('/api/v1/admin/users').reply(403, {
errors: [{ code: 'PERM_001', message: 'Insufficient permissions' }],
});
await expect(
apiClient.instance.get('/api/v1/admin/users')
).rejects.toThrow();
// Should not clear auth or refresh token
expect(mockAuthStore.clearAuth).not.toHaveBeenCalled();
expect(mockAuthStore.setTokens).not.toHaveBeenCalled();
});
});
describe('Response Interceptor - 404 Not Found', () => {
it('should pass through 404 errors', async () => {
mock.onGet('/api/v1/nonexistent').reply(404, {
errors: [{ code: 'NOT_FOUND', message: 'Resource not found' }],
});
await expect(
apiClient.instance.get('/api/v1/nonexistent')
).rejects.toThrow();
});
});
describe('Response Interceptor - 429 Rate Limit', () => {
it('should pass through 429 errors', async () => {
mock.onPost('/api/v1/auth/login').reply(429, {
errors: [{ code: 'RATE_001', message: 'Too many requests' }],
});
await expect(
apiClient.instance.post('/api/v1/auth/login', {
email: 'user@example.com',
password: 'password',
})
).rejects.toThrow();
});
});
describe('Response Interceptor - 5xx Server Errors', () => {
it('should pass through 500 errors', async () => {
mock.onGet('/api/v1/data').reply(500, {
errors: [{ code: 'SERVER_ERROR', message: 'Internal server error' }],
});
await expect(
apiClient.instance.get('/api/v1/data')
).rejects.toThrow();
});
it('should pass through 502 errors', async () => {
mock.onGet('/api/v1/data').reply(502, {
errors: [{ code: 'SERVER_ERROR', message: 'Bad gateway' }],
});
await expect(
apiClient.instance.get('/api/v1/data')
).rejects.toThrow();
});
it('should pass through 503 errors', async () => {
mock.onGet('/api/v1/data').reply(503, {
errors: [{ code: 'SERVER_ERROR', message: 'Service unavailable' }],
});
await expect(
apiClient.instance.get('/api/v1/data')
).rejects.toThrow();
});
});
describe('Network Errors', () => {
it('should handle network errors gracefully', async () => {
mock.onGet('/api/v1/test').networkError();
await expect(
apiClient.instance.get('/api/v1/test')
).rejects.toThrow();
});
it('should handle timeout errors', async () => {
mock.onGet('/api/v1/test').timeout();
await expect(
apiClient.instance.get('/api/v1/test')
).rejects.toThrow();
});
});
describe('Successful Requests', () => {
it('should handle successful GET requests', async () => {
mock.onGet('/api/v1/users').reply(200, {
users: [
{ id: 1, name: 'User 1' },
{ id: 2, name: 'User 2' },
],
});
const response = await apiClient.instance.get('/api/v1/users');
expect(response.status).toBe(200);
expect(response.data.users).toHaveLength(2);
});
it('should handle successful POST requests', async () => {
mock.onPost('/api/v1/users').reply(201, {
id: 1,
name: 'New User',
email: 'newuser@example.com',
});
const response = await apiClient.instance.post('/api/v1/users', {
name: 'New User',
email: 'newuser@example.com',
});
expect(response.status).toBe(201);
expect(response.data.name).toBe('New User');
});
it('should handle successful PUT requests', async () => {
mock.onPut('/api/v1/users/1').reply(200, {
id: 1,
name: 'Updated User',
});
const response = await apiClient.instance.put('/api/v1/users/1', {
name: 'Updated User',
});
expect(response.status).toBe(200);
expect(response.data.name).toBe('Updated User');
});
it('should handle successful DELETE requests', async () => {
mock.onDelete('/api/v1/users/1').reply(200, {
success: true,
message: 'User deleted',
});
const response = await apiClient.instance.delete('/api/v1/users/1');
expect(response.status).toBe(200);
expect(response.data.success).toBe(true);
});
});
describe('Edge Cases', () => {
it('should handle empty response bodies', async () => {
mock.onGet('/api/v1/test').reply(204);
const response = await apiClient.instance.get('/api/v1/test');
expect(response.status).toBe(204);
});
it('should handle no refresh token available during 401', async () => {
mockAuthStore.accessToken = 'expired-token';
mockAuthStore.refreshToken = null; // No refresh token
// Mock window.location
delete (global as any).window;
(global as any).window = {
location: { href: '', pathname: '/dashboard' },
};
mock.onGet('/api/v1/protected').reply(401);
await expect(
apiClient.instance.get('/api/v1/protected')
).rejects.toThrow();
expect(mockAuthStore.clearAuth).toHaveBeenCalled();
expect(window.location.href).toContain('/login');
});
it('should preserve query parameters during retry', async () => {
mockAuthStore.accessToken = 'expired-token';
mockAuthStore.refreshToken = 'valid-refresh-token';
let requestCount = 0;
mock.onGet('/api/v1/test').reply((config) => {
requestCount++;
// Verify query params are preserved
expect(config.params).toEqual({ filter: 'active', page: 1 });
if (requestCount === 1) {
return [401];
} else {
return [200, { success: true }];
}
});
mock.onPost('/api/v1/auth/refresh').reply(200, {
access_token: 'new-access-token',
refresh_token: 'new-refresh-token',
token_type: 'bearer',
});
const response = await apiClient.instance.get('/api/v1/test', {
params: { filter: 'active', page: 1 },
});
expect(response.status).toBe(200);
expect(requestCount).toBe(2);
});
it('should handle custom headers during retry', async () => {
mockAuthStore.accessToken = 'expired-token';
mockAuthStore.refreshToken = 'valid-refresh-token';
let requestCount = 0;
mock.onGet('/api/v1/test').reply((config) => {
requestCount++;
// Verify custom header is preserved
expect(config.headers?.['X-Custom-Header']).toBe('test-value');
if (requestCount === 1) {
return [401];
} else {
return [200, { success: true }];
}
});
mock.onPost('/api/v1/auth/refresh').reply(200, {
access_token: 'new-access-token',
refresh_token: 'new-refresh-token',
token_type: 'bearer',
});
await apiClient.instance.get('/api/v1/test', {
headers: { 'X-Custom-Header': 'test-value' },
});
expect(requestCount).toBe(2);
});
it('should only mark request as retried once', async () => {
mockAuthStore.accessToken = 'expired-token';
mockAuthStore.refreshToken = 'valid-refresh-token';
// This endpoint will keep returning 401 to test that we don't retry infinitely
let requestCount = 0;
mock.onGet('/api/v1/protected').reply(() => {
requestCount++;
return [401, { errors: [{ code: 'AUTH_003', message: 'Token expired' }] }];
});
mock.onPost('/api/v1/auth/refresh').reply(200, {
access_token: 'new-access-token',
refresh_token: 'new-refresh-token',
token_type: 'bearer',
});
await expect(
apiClient.instance.get('/api/v1/protected')
).rejects.toThrow();
// Should only retry once (original + 1 retry = 2 total requests)
expect(requestCount).toBe(2);
});
});
});

View File

@@ -0,0 +1,651 @@
/**
* Comprehensive tests for API error handling
*
* Tests cover:
* - Type guards (isAxiosError, isAPIErrorArray)
* - Error parsing for all scenarios (network, HTTP status, structured errors)
* - Field error extraction
* - General error extraction
* - Edge cases and error recovery
*/
import { AxiosError } from 'axios';
import {
parseAPIError,
getErrorMessage,
getFieldErrors,
getGeneralError,
isAPIErrorArray,
ERROR_MESSAGES,
type APIError,
} from '@/lib/api/errors';
describe('API Error Handling', () => {
describe('isAPIErrorArray', () => {
it('should return true for valid APIError array', () => {
const errors: APIError[] = [
{ code: 'AUTH_001', message: 'Invalid credentials' },
{ code: 'VAL_002', message: 'Invalid email', field: 'email' },
];
expect(isAPIErrorArray(errors)).toBe(true);
});
it('should return false for non-array', () => {
expect(isAPIErrorArray('not an array')).toBe(false);
expect(isAPIErrorArray(null)).toBe(false);
expect(isAPIErrorArray(undefined)).toBe(false);
expect(isAPIErrorArray({})).toBe(false);
});
it('should return false for empty array', () => {
expect(isAPIErrorArray([])).toBe(true); // Empty array is technically valid
});
it('should return false for array with invalid elements', () => {
const invalidErrors = [
{ code: 'AUTH_001' }, // missing message
{ message: 'Invalid credentials' }, // missing code
'string', // not an object
];
expect(isAPIErrorArray(invalidErrors)).toBe(false);
});
it('should handle optional field property', () => {
const errorsWithField: APIError[] = [
{ code: 'VAL_001', message: 'Invalid input', field: 'email' },
];
const errorsWithoutField: APIError[] = [
{ code: 'AUTH_001', message: 'Invalid credentials' },
];
expect(isAPIErrorArray(errorsWithField)).toBe(true);
expect(isAPIErrorArray(errorsWithoutField)).toBe(true);
});
it('should reject invalid field types', () => {
const invalidFieldType = [
{ code: 'VAL_001', message: 'Invalid', field: 123 }, // field must be string
];
expect(isAPIErrorArray(invalidFieldType)).toBe(false);
});
});
describe('parseAPIError', () => {
describe('Non-AxiosError handling', () => {
it('should handle generic Error objects', () => {
const error = new Error('Something went wrong');
const result = parseAPIError(error);
expect(result).toEqual([
{
code: 'UNKNOWN',
message: 'Something went wrong',
},
]);
});
it('should handle non-Error objects', () => {
const error = { some: 'object' };
const result = parseAPIError(error);
expect(result).toEqual([
{
code: 'UNKNOWN',
message: ERROR_MESSAGES['UNKNOWN'],
},
]);
});
it('should handle null and undefined', () => {
expect(parseAPIError(null)).toEqual([
{ code: 'UNKNOWN', message: ERROR_MESSAGES['UNKNOWN'] },
]);
expect(parseAPIError(undefined)).toEqual([
{ code: 'UNKNOWN', message: ERROR_MESSAGES['UNKNOWN'] },
]);
});
it('should handle strings', () => {
const result = parseAPIError('some error string');
expect(result).toEqual([
{ code: 'UNKNOWN', message: ERROR_MESSAGES['UNKNOWN'] },
]);
});
});
describe('Backend structured errors', () => {
it('should parse structured error response', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 400,
data: {
success: false,
errors: [
{ code: 'AUTH_001', message: 'Invalid credentials' },
{ code: 'VAL_002', message: 'Invalid email', field: 'email' },
],
},
statusText: 'Bad Request',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{ code: 'AUTH_001', message: 'Invalid credentials' },
{ code: 'VAL_002', message: 'Invalid email', field: 'email' },
]);
});
it('should handle single error in array', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 400,
data: {
errors: [{ code: 'USER_001', message: 'User not found' }],
},
statusText: 'Bad Request',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([{ code: 'USER_001', message: 'User not found' }]);
});
it('should handle multiple field errors', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Validation failed',
response: {
status: 422,
data: {
errors: [
{ code: 'VAL_002', message: 'Invalid email', field: 'email' },
{ code: 'VAL_003', message: 'Weak password', field: 'password' },
{ code: 'VAL_004', message: 'Required', field: 'first_name' },
],
},
statusText: 'Unprocessable Entity',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toHaveLength(3);
expect(result[0].field).toBe('email');
expect(result[1].field).toBe('password');
expect(result[2].field).toBe('first_name');
});
});
describe('Network errors', () => {
it('should handle network error (no response)', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Network Error',
response: undefined,
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'NETWORK_ERROR',
message: ERROR_MESSAGES['NETWORK_ERROR'],
},
]);
});
it('should handle timeout error', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'timeout of 5000ms exceeded',
response: undefined,
code: 'ECONNABORTED',
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'NETWORK_ERROR',
message: ERROR_MESSAGES['NETWORK_ERROR'],
},
]);
});
});
describe('HTTP status-based errors', () => {
it('should handle 401 Unauthorized', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 401,
data: {},
statusText: 'Unauthorized',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'AUTH_003',
message: ERROR_MESSAGES['AUTH_003'],
},
]);
});
it('should handle 403 Forbidden', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 403,
data: {},
statusText: 'Forbidden',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'FORBIDDEN',
message: ERROR_MESSAGES['FORBIDDEN'],
},
]);
});
it('should handle 404 Not Found', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 404,
data: {},
statusText: 'Not Found',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'NOT_FOUND',
message: ERROR_MESSAGES['NOT_FOUND'],
},
]);
});
it('should handle 429 Too Many Requests', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 429,
data: {},
statusText: 'Too Many Requests',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'RATE_LIMIT',
message: ERROR_MESSAGES['RATE_LIMIT'],
},
]);
});
it('should handle 500 Internal Server Error', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 500,
data: {},
statusText: 'Internal Server Error',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'SERVER_ERROR',
message: ERROR_MESSAGES['SERVER_ERROR'],
},
]);
});
it('should handle 502 Bad Gateway', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 502,
data: {},
statusText: 'Bad Gateway',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'SERVER_ERROR',
message: ERROR_MESSAGES['SERVER_ERROR'],
},
]);
});
it('should handle 503 Service Unavailable', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 503,
data: {},
statusText: 'Service Unavailable',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'SERVER_ERROR',
message: ERROR_MESSAGES['SERVER_ERROR'],
},
]);
});
});
describe('Fallback error handling', () => {
it('should handle unrecognized status code with message', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Custom error message',
response: {
status: 418, // I'm a teapot
data: {},
statusText: "I'm a teapot",
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'UNKNOWN',
message: 'Custom error message',
},
]);
});
it('should handle response with non-structured data', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 400,
data: 'Plain text error',
statusText: 'Bad Request',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
expect(result).toEqual([
{
code: 'UNKNOWN',
message: 'Request failed',
},
]);
});
});
describe('Priority testing', () => {
it('should prioritize structured errors over status codes', () => {
const axiosError: Partial<AxiosError> = {
isAxiosError: true,
message: 'Request failed',
response: {
status: 401,
data: {
errors: [
{ code: 'CUSTOM_ERROR', message: 'Custom structured error' },
],
},
statusText: 'Unauthorized',
headers: {},
config: {} as any,
},
};
const result = parseAPIError(axiosError);
// Should return structured error, not the 401 default
expect(result).toEqual([
{ code: 'CUSTOM_ERROR', message: 'Custom structured error' },
]);
});
});
});
describe('getErrorMessage', () => {
it('should return message for known error code', () => {
expect(getErrorMessage('AUTH_001')).toBe('Invalid email or password');
expect(getErrorMessage('USER_002')).toBe('This email is already registered');
expect(getErrorMessage('VAL_002')).toBe('Email format is invalid');
});
it('should return UNKNOWN message for unknown code', () => {
expect(getErrorMessage('UNKNOWN_CODE')).toBe(ERROR_MESSAGES['UNKNOWN']);
expect(getErrorMessage('')).toBe(ERROR_MESSAGES['UNKNOWN']);
});
it('should handle all documented error codes', () => {
const codes = [
'AUTH_001',
'AUTH_002',
'AUTH_003',
'AUTH_004',
'USER_001',
'USER_002',
'USER_003',
'USER_004',
'VAL_001',
'VAL_002',
'VAL_003',
'VAL_004',
'ORG_001',
'ORG_002',
'ORG_003',
'PERM_001',
'PERM_002',
'PERM_003',
'RATE_001',
'SESSION_001',
'SESSION_002',
'SESSION_003',
'NETWORK_ERROR',
'SERVER_ERROR',
'UNKNOWN',
'FORBIDDEN',
'NOT_FOUND',
'RATE_LIMIT',
];
codes.forEach((code) => {
const message = getErrorMessage(code);
expect(message).toBeTruthy();
expect(typeof message).toBe('string');
expect(message.length).toBeGreaterThan(0);
});
});
});
describe('getFieldErrors', () => {
it('should extract field-specific errors', () => {
const errors: APIError[] = [
{ code: 'VAL_002', message: 'Invalid email format', field: 'email' },
{ code: 'VAL_003', message: 'Password too weak', field: 'password' },
{ code: 'AUTH_001', message: 'Invalid credentials' }, // no field
];
const result = getFieldErrors(errors);
expect(result).toEqual({
email: 'Invalid email format',
password: 'Password too weak',
});
});
it('should return empty object when no field errors', () => {
const errors: APIError[] = [
{ code: 'AUTH_001', message: 'Invalid credentials' },
{ code: 'SERVER_ERROR', message: 'Server error' },
];
const result = getFieldErrors(errors);
expect(result).toEqual({});
});
it('should return empty object for empty array', () => {
const result = getFieldErrors([]);
expect(result).toEqual({});
});
it('should use error code message if message is missing', () => {
const errors: APIError[] = [
{ code: 'VAL_002', message: '', field: 'email' },
];
const result = getFieldErrors(errors);
expect(result.email).toBe(ERROR_MESSAGES['VAL_002']);
});
it('should handle multiple errors for same field (last one wins)', () => {
const errors: APIError[] = [
{ code: 'VAL_001', message: 'First error', field: 'email' },
{ code: 'VAL_002', message: 'Second error', field: 'email' },
];
const result = getFieldErrors(errors);
expect(result.email).toBe('Second error');
});
});
describe('getGeneralError', () => {
it('should return first non-field error', () => {
const errors: APIError[] = [
{ code: 'VAL_002', message: 'Invalid email', field: 'email' },
{ code: 'AUTH_001', message: 'Invalid credentials' },
{ code: 'SERVER_ERROR', message: 'Server error' },
];
const result = getGeneralError(errors);
expect(result).toBe('Invalid credentials');
});
it('should return undefined when only field errors exist', () => {
const errors: APIError[] = [
{ code: 'VAL_002', message: 'Invalid email', field: 'email' },
{ code: 'VAL_003', message: 'Weak password', field: 'password' },
];
const result = getGeneralError(errors);
expect(result).toBeUndefined();
});
it('should return undefined for empty array', () => {
const result = getGeneralError([]);
expect(result).toBeUndefined();
});
it('should use error code message if message is missing', () => {
const errors: APIError[] = [
{ code: 'AUTH_001', message: '' },
];
const result = getGeneralError(errors);
expect(result).toBe(ERROR_MESSAGES['AUTH_001']);
});
it('should skip field errors and find general error', () => {
const errors: APIError[] = [
{ code: 'VAL_001', message: 'Field error 1', field: 'field1' },
{ code: 'VAL_002', message: 'Field error 2', field: 'field2' },
{ code: 'VAL_003', message: 'Field error 3', field: 'field3' },
{ code: 'SERVER_ERROR', message: 'General server error' },
];
const result = getGeneralError(errors);
expect(result).toBe('General server error');
});
});
describe('Error message completeness', () => {
it('should have non-empty messages for all error codes', () => {
Object.entries(ERROR_MESSAGES).forEach(([code, message]) => {
expect(message).toBeTruthy();
expect(message.length).toBeGreaterThan(0);
expect(message).not.toBe('');
});
});
it('should have user-friendly messages', () => {
// Check that messages don't contain technical jargon or error codes
Object.entries(ERROR_MESSAGES).forEach(([code, message]) => {
expect(message).not.toContain('null');
expect(message).not.toContain('undefined');
expect(message).not.toContain('Error:');
// Messages should start with capital letter
expect(message[0]).toMatch(/[A-Z]/);
});
});
});
});

View File

@@ -0,0 +1,486 @@
/**
* Comprehensive tests for API type guards and extensions
*
* Tests cover:
* - TokenWithUser type guard (isTokenWithUser)
* - SuccessResponse type guard (isSuccessResponse)
* - Edge cases and type safety
*/
import {
isTokenWithUser,
isSuccessResponse,
type TokenWithUser,
type SuccessResponse,
} from '@/lib/api/types';
describe('API Type Guards', () => {
describe('isTokenWithUser', () => {
it('should return true for valid TokenWithUser', () => {
const token: TokenWithUser = {
access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
refresh_token: 'refresh_token_here',
token_type: 'bearer',
user: {
id: '123',
email: 'user@example.com',
first_name: 'John',
last_name: 'Doe',
is_active: true,
is_superuser: false,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
expires_in: 3600,
};
expect(isTokenWithUser(token)).toBe(true);
});
it('should return true for valid TokenWithUser without optional fields', () => {
const token = {
access_token: 'token123',
token_type: 'bearer',
user: {
id: '123',
email: 'user@example.com',
first_name: 'John',
last_name: 'Doe',
is_active: true,
is_superuser: false,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
// No refresh_token
// No expires_in
};
expect(isTokenWithUser(token)).toBe(true);
});
it('should return false when token is null', () => {
expect(isTokenWithUser(null)).toBe(false);
});
it('should return false when token is undefined', () => {
expect(isTokenWithUser(undefined)).toBe(false);
});
it('should return false when token is not an object', () => {
expect(isTokenWithUser('string')).toBe(false);
expect(isTokenWithUser(123)).toBe(false);
expect(isTokenWithUser(true)).toBe(false);
expect(isTokenWithUser([])).toBe(false);
});
it('should return false when access_token is missing', () => {
const token = {
// No access_token
token_type: 'bearer',
user: {
id: '123',
email: 'user@example.com',
first_name: 'John',
last_name: 'Doe',
is_active: true,
is_superuser: false,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
};
expect(isTokenWithUser(token)).toBe(false);
});
it('should return false when access_token is not a string', () => {
const token = {
access_token: 123, // Not a string
token_type: 'bearer',
user: {
id: '123',
email: 'user@example.com',
first_name: 'John',
last_name: 'Doe',
is_active: true,
is_superuser: false,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
};
expect(isTokenWithUser(token)).toBe(false);
});
it('should return false when user is missing', () => {
const token = {
access_token: 'token123',
token_type: 'bearer',
// No user
};
expect(isTokenWithUser(token)).toBe(false);
});
it('should return false when user is null', () => {
const token = {
access_token: 'token123',
token_type: 'bearer',
user: null,
};
expect(isTokenWithUser(token)).toBe(false);
});
it('should return false when user is not an object', () => {
const token = {
access_token: 'token123',
token_type: 'bearer',
user: 'not an object',
};
expect(isTokenWithUser(token)).toBe(false);
});
it('should return false when user is an array', () => {
const token = {
access_token: 'token123',
token_type: 'bearer',
user: [],
};
expect(isTokenWithUser(token)).toBe(false);
});
it('should return true even with extra fields', () => {
const token = {
access_token: 'token123',
token_type: 'bearer',
user: {
id: '123',
email: 'user@example.com',
first_name: 'John',
last_name: 'Doe',
is_active: true,
is_superuser: false,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
extra_field: 'should not break validation',
another_field: 123,
};
expect(isTokenWithUser(token)).toBe(true);
});
it('should return false when access_token is empty string', () => {
const token = {
access_token: '', // Empty string
token_type: 'bearer',
user: {
id: '123',
email: 'user@example.com',
first_name: 'John',
last_name: 'Doe',
is_active: true,
is_superuser: false,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
};
// Type guard doesn't check for empty string, just type
expect(isTokenWithUser(token)).toBe(true);
});
it('should handle minimal valid user object', () => {
const token = {
access_token: 'token123',
user: {
// Minimal user - type guard only checks if it's an object
},
};
expect(isTokenWithUser(token)).toBe(true);
});
it('should handle edge case: empty object', () => {
expect(isTokenWithUser({})).toBe(false);
});
it('should handle edge case: object with only access_token', () => {
const token = {
access_token: 'token123',
};
expect(isTokenWithUser(token)).toBe(false);
});
it('should handle edge case: object with only user', () => {
const token = {
user: { id: '123' },
};
expect(isTokenWithUser(token)).toBe(false);
});
});
describe('isSuccessResponse', () => {
it('should return true for valid SuccessResponse', () => {
const response: SuccessResponse = {
success: true,
message: 'Operation completed successfully',
};
expect(isSuccessResponse(response)).toBe(true);
});
it('should return false when response is null', () => {
expect(isSuccessResponse(null)).toBe(false);
});
it('should return false when response is undefined', () => {
expect(isSuccessResponse(undefined)).toBe(false);
});
it('should return false when response is not an object', () => {
expect(isSuccessResponse('string')).toBe(false);
expect(isSuccessResponse(123)).toBe(false);
expect(isSuccessResponse(true)).toBe(false);
expect(isSuccessResponse([])).toBe(false);
});
it('should return false when success is missing', () => {
const response = {
// No success
message: 'Some message',
};
expect(isSuccessResponse(response)).toBe(false);
});
it('should return false when success is not true', () => {
const response = {
success: false, // Must be true
message: 'Some message',
};
expect(isSuccessResponse(response)).toBe(false);
});
it('should return false when success is truthy but not true', () => {
const response1 = {
success: 'true', // String, not boolean
message: 'Some message',
};
const response2 = {
success: 1, // Number, not boolean
message: 'Some message',
};
expect(isSuccessResponse(response1)).toBe(false);
expect(isSuccessResponse(response2)).toBe(false);
});
it('should return false when message is missing', () => {
const response = {
success: true,
// No message
};
expect(isSuccessResponse(response)).toBe(false);
});
it('should return false when message is not a string', () => {
const response1 = {
success: true,
message: 123, // Number
};
const response2 = {
success: true,
message: null, // Null
};
const response3 = {
success: true,
message: { text: 'message' }, // Object
};
expect(isSuccessResponse(response1)).toBe(false);
expect(isSuccessResponse(response2)).toBe(false);
expect(isSuccessResponse(response3)).toBe(false);
});
it('should return true even with extra fields', () => {
const response = {
success: true,
message: 'Success',
extra_field: 'should not break validation',
data: { some: 'data' },
};
expect(isSuccessResponse(response)).toBe(true);
});
it('should return true with empty message string', () => {
const response = {
success: true,
message: '', // Empty but still a string
};
expect(isSuccessResponse(response)).toBe(true);
});
it('should handle edge case: empty object', () => {
expect(isSuccessResponse({})).toBe(false);
});
it('should handle edge case: object with only success', () => {
const response = {
success: true,
};
expect(isSuccessResponse(response)).toBe(false);
});
it('should handle edge case: object with only message', () => {
const response = {
message: 'Some message',
};
expect(isSuccessResponse(response)).toBe(false);
});
});
describe('Type narrowing in practice', () => {
it('should allow safe access to TokenWithUser properties', () => {
const response: unknown = {
access_token: 'token123',
user: {
id: '123',
email: 'test@example.com',
first_name: 'Test',
last_name: 'User',
is_active: true,
is_superuser: false,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
expires_in: 3600,
};
if (isTokenWithUser(response)) {
// TypeScript should know response is TokenWithUser here
expect(response.access_token).toBe('token123');
expect(response.user.email).toBe('test@example.com');
expect(response.expires_in).toBe(3600);
} else {
fail('Should have been recognized as TokenWithUser');
}
});
it('should allow safe access to SuccessResponse properties', () => {
const response: unknown = {
success: true,
message: 'Password reset successful',
};
if (isSuccessResponse(response)) {
// TypeScript should know response is SuccessResponse here
expect(response.success).toBe(true);
expect(response.message).toBe('Password reset successful');
} else {
fail('Should have been recognized as SuccessResponse');
}
});
it('should properly narrow union types', () => {
function processResponse(response: unknown): string {
if (isTokenWithUser(response)) {
return `Token for ${response.user.email}`;
} else if (isSuccessResponse(response)) {
return response.message;
} else {
return 'Unknown response type';
}
}
const tokenResponse = {
access_token: 'token',
user: {
email: 'test@example.com',
id: '1',
first_name: 'Test',
last_name: 'User',
is_active: true,
is_superuser: false,
created_at: '2024-01-01',
updated_at: '2024-01-01',
},
};
const successResponse = {
success: true,
message: 'Done',
};
expect(processResponse(tokenResponse)).toBe('Token for test@example.com');
expect(processResponse(successResponse)).toBe('Done');
expect(processResponse('invalid')).toBe('Unknown response type');
});
});
describe('Real-world scenarios', () => {
it('should validate login response with user data', () => {
const loginResponse = {
access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjMifQ.abc',
refresh_token: 'refresh_abc123',
token_type: 'bearer',
expires_in: 3600,
user: {
id: '123',
email: 'user@example.com',
first_name: 'John',
last_name: 'Doe',
is_active: true,
is_superuser: false,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
};
expect(isTokenWithUser(loginResponse)).toBe(true);
});
it('should reject login response without user data', () => {
const loginResponse = {
access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjMifQ.abc',
refresh_token: 'refresh_abc123',
token_type: 'bearer',
expires_in: 3600,
// Missing user field
};
expect(isTokenWithUser(loginResponse)).toBe(false);
});
it('should validate password reset success response', () => {
const resetResponse = {
success: true,
message: 'Password reset email sent. Please check your inbox.',
};
expect(isSuccessResponse(resetResponse)).toBe(true);
});
it('should validate logout success response', () => {
const logoutResponse = {
success: true,
message: 'Successfully logged out',
};
expect(isSuccessResponse(logoutResponse)).toBe(true);
});
});
});