UNPKG

@dbs-portal/core-api

Version:

HTTP client and API utilities for DBS Portal

256 lines 11.8 kB
/** * MSW integration tests */ import { describe, it, expect, afterEach, beforeAll, afterAll } from 'vitest'; import { http, HttpResponse } from 'msw'; import { setupMSWTesting, mockHelpers, testFactories } from './test-utils'; import { getMockConfig, updateMockConfig, initializeMockConfig } from '../config'; import { isMockingEnabled, getMockingMode } from '../config/environment'; import { createApiUrl, MSW_HEADERS } from './msw-utils'; describe('MSW Integration', () => { const msw = setupMSWTesting(); beforeAll(() => { // Initialize mock configuration for testing initializeMockConfig({ enabled: true, mode: 'testing', logging: false, }); }); afterEach(() => { msw.cleanup(); }); afterAll(() => { msw.teardown(); }); describe('Environment Detection', () => { it('should detect test environment correctly', () => { expect(getMockingMode()).toBe('testing'); expect(isMockingEnabled()).toBe(true); }); it('should have correct mock configuration for testing', () => { const config = getMockConfig(); expect(config.enabled).toBe(true); expect(config.mode).toBe('testing'); }); }); describe('Mock Configuration', () => { it('should allow updating mock configuration', () => { const originalConfig = getMockConfig(); updateMockConfig({ delay: 100, logging: false, }); const updatedConfig = getMockConfig(); expect(updatedConfig.delay).toBe(100); expect(updatedConfig.logging).toBe(false); expect(updatedConfig.enabled).toBe(originalConfig.enabled); // Should preserve other settings }); it('should merge error simulation config correctly', () => { updateMockConfig({ errorSimulation: { networkErrorRate: 0.1, serverErrorRate: 0.05, }, }); const config = getMockConfig(); expect(config.errorSimulation?.networkErrorRate).toBe(0.1); expect(config.errorSimulation?.serverErrorRate).toBe(0.05); }); }); describe('Handler Management', () => { it('should handle default handlers correctly', async () => { // Test health endpoint (from default handlers) const response = await fetch(createApiUrl('/api/health'), { // Add this to ensure the test works in Node environment // where localhost may resolve to multiple addresses headers: MSW_HEADERS }); const data = await response.json(); expect(response.ok).toBe(true); expect(data.success).toBe(true); expect(data.data.status).toBe('healthy'); }); it('should handle auth handlers correctly', async () => { // Test login endpoint (from auth handlers) const response = await fetch(createApiUrl('/api/auth/login'), { method: 'POST', headers: { 'Content-Type': 'application/json', ...MSW_HEADERS // Ensure MSW intercepts this request }, body: JSON.stringify({ email: 'test@example.com', password: 'password123', }), }); const data = await response.json(); expect(response.ok).toBe(true); expect(data.success).toBe(true); expect(data.data.tokens.accessToken).toBeDefined(); }); it('should allow adding custom handlers', () => { msw.addHandlers(http.get(createApiUrl('/api/custom'), () => { return HttpResponse.json(mockHelpers.success({ custom: true })); })); // Handler should be active immediately expect(msw.server.listHandlers().length).toBeGreaterThan(6); // Should have added the custom handler }); it('should reset handlers correctly', () => { // Add custom handler msw.addHandlers(http.get(createApiUrl('/api/temporary'), () => { return HttpResponse.json(mockHelpers.success({ temporary: true })); })); const initialHandlerCount = msw.server.listHandlers().length; // Reset should remove custom handlers msw.resetHandlers(); expect(msw.server.listHandlers().length).toBeLessThanOrEqual(initialHandlerCount); }); }); describe('Response Helpers', () => { it('should create success responses correctly', () => { const data = { id: 1, name: 'Test' }; const response = mockHelpers.success(data, 'Custom message'); expect(response.success).toBe(true); expect(response.data).toEqual(data); expect(response.message).toBe('Custom message'); expect(response.meta.timestamp).toBeDefined(); expect(response.meta.requestId).toBeDefined(); }); it('should create error responses correctly', () => { const response = mockHelpers.error('Test error', 'TEST_CODE', 400); expect(response.success).toBe(false); expect(response.message).toBe('Test error'); expect(response.errors).toHaveLength(1); expect(response?.errors[0]?.code).toBe('TEST_CODE'); expect(response?.errors[0]?.message).toBe('Test error'); }); it('should create validation error responses correctly', () => { const errors = [ { field: 'email', message: 'Email is required' }, { field: 'password', message: 'Password is too short' }, ]; const response = mockHelpers.validationError(errors); expect(response.success).toBe(false); expect(response.message).toBe('Validation failed'); expect(response.errors).toHaveLength(2); expect(response.errors[0]?.field).toBe('email'); expect(response.errors[1]?.field).toBe('password'); }); it('should create paginated responses correctly', () => { const items = Array.from({ length: 25 }, (_, i) => ({ id: i + 1, name: `Item ${i + 1}` })); const response = mockHelpers.paginated(items, 2, 10); expect(response.success).toBe(true); expect(response.data.items).toHaveLength(10); expect(response.data.currentPage).toBe(2); expect(response.data.totalCount).toBe(25); expect(response.data.totalPages).toBe(3); expect(response.data.hasNextPage).toBe(true); expect(response.data.hasPreviousPage).toBe(true); }); }); describe('Test Factories', () => { it('should create test users correctly', () => { const user = testFactories.user(); expect(user.id).toBeDefined(); expect(user.email).toBe('test@example.com'); expect(user.username).toBe('testuser'); expect(user.firstName).toBe('Test'); expect(user.lastName).toBe('User'); expect(user.isActive).toBe(true); expect(user.createdAt).toBeDefined(); expect(user.updatedAt).toBeDefined(); }); it('should allow overriding user properties', () => { const user = testFactories.user({ email: 'custom@example.com', firstName: 'Custom', isActive: false, }); expect(user.email).toBe('custom@example.com'); expect(user.firstName).toBe('Custom'); expect(user.isActive).toBe(false); expect(user.lastName).toBe('User'); // Should keep default }); it('should create test files correctly', () => { const file = testFactories.file(); expect(file.id).toBeDefined(); expect(file.filename).toBe('test-file.txt'); expect(file.mimeType).toBe('text/plain'); expect(file.size).toBe(1024); expect(file.url).toBe('/uploads/test-file.txt'); expect(file.uploadedAt).toBeDefined(); }); it('should create auth tokens correctly', () => { const tokens = testFactories.authTokens(); expect(tokens.accessToken).toBe('mock_access_token'); expect(tokens.refreshToken).toBe('mock_refresh_token'); expect(tokens.tokenType).toBe('Bearer'); expect(tokens.expiresAt).toBeDefined(); }); }); describe('Request/Response Flow', () => { it('should handle request parameters correctly', async () => { msw.addHandlers(http.get(createApiUrl('/api/test/:id'), ({ params, request }) => { const url = new URL(request.url); const query = url.searchParams.get('query'); return HttpResponse.json(mockHelpers.success({ id: params['id'], query, method: request.method, })); })); const response = await fetch(createApiUrl('/api/test/123?query=test'), { headers: MSW_HEADERS // Ensure MSW intercepts this request }); const data = await response.json(); expect(data.success).toBe(true); expect(data.data.id).toBe('123'); expect(data.data.query).toBe('test'); expect(data.data.method).toBe('GET'); }); it('should handle request body correctly', async () => { msw.addHandlers(http.post(createApiUrl('/api/echo'), async ({ request }) => { const body = await request.json(); return HttpResponse.json(mockHelpers.success({ receivedBody: body, contentType: request.headers.get('content-type'), })); })); const testData = { message: 'Hello, MSW!' }; const response = await fetch(createApiUrl('/api/echo'), { method: 'POST', headers: { 'Content-Type': 'application/json', ...MSW_HEADERS // Ensure MSW intercepts this request }, body: JSON.stringify(testData), }); const data = await response.json(); expect(data.success).toBe(true); expect(data.data.receivedBody).toEqual(testData); expect(data.data.contentType).toBe('application/json'); }); it('should handle headers correctly', async () => { msw.addHandlers(http.get(createApiUrl('/api/headers'), ({ request }) => { return HttpResponse.json(mockHelpers.success({ authorization: request.headers.get('authorization'), userAgent: request.headers.get('user-agent'), customHeader: request.headers.get('x-custom-header'), })); })); const response = await fetch(createApiUrl('/api/headers'), { headers: { 'Authorization': 'Bearer test-token', 'X-Custom-Header': 'custom-value', ...MSW_HEADERS, // Ensure MSW intercepts this request }, }); const data = await response.json(); expect(data.success).toBe(true); expect(data.data.authorization).toBe('Bearer test-token'); expect(data.data.customHeader).toBe('custom-value'); }); }); }); //# sourceMappingURL=msw-integration.test.js.map