Files
api-codegen/tests/helpers/mock-server.ts
2025-10-28 09:58:44 +03:00

88 lines
3.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
/**
* Создание mock HTTP сервера для тестирования
*/
export function createMockServer() {
const handlers = [
// Mock для успешного GET запроса
http.get('https://api.example.com/users', () => {
return HttpResponse.json([
{ id: '1', email: 'user1@example.com', name: 'User 1' },
{ id: '2', email: 'user2@example.com', name: 'User 2' },
]);
}),
// Mock для GET с параметрами
http.get('https://api.example.com/users/:id', ({ params }) => {
const { id } = params;
if (id === '1') {
return HttpResponse.json({ id: '1', email: 'user1@example.com', name: 'User 1' });
}
return HttpResponse.json({ error: 'Not found' }, { status: 404 });
}),
// Mock для POST запроса
http.post('https://api.example.com/users', async ({ request }) => {
const body = await request.json() as Record<string, any>;
return HttpResponse.json(
{ id: '3', ...body },
{ status: 201 }
);
}),
// Mock для PATCH запроса
http.patch('https://api.example.com/users/:id', async ({ request, params }) => {
const body = await request.json() as Record<string, any>;
return HttpResponse.json({ id: params.id, ...body });
}),
// Mock для DELETE запроса
http.delete('https://api.example.com/users/:id', () => {
return new HttpResponse(null, { status: 204 });
}),
// Mock для авторизации
http.post('https://api.example.com/auth/login', async ({ request }) => {
const body = await request.json() as any;
if (body.email === 'test@example.com' && body.password === 'password') {
return HttpResponse.json({ token: 'mock-jwt-token' });
}
return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
}),
// Mock для защищенного endpoint
http.get('https://api.example.com/profile', ({ request }) => {
const auth = request.headers.get('Authorization');
if (auth && auth.startsWith('Bearer ')) {
return HttpResponse.json({ id: '1', email: 'test@example.com' });
}
return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
}),
// Mock для ошибки сервера
http.get('https://api.example.com/error', () => {
return HttpResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}),
// Mock для network error
http.get('https://api.example.com/network-error', () => {
return HttpResponse.error();
}),
];
const server = setupServer(...handlers);
return {
server,
start: () => server.listen({ onUnhandledRequest: 'warn' }),
stop: () => server.close(),
reset: () => server.resetHandlers(),
};
}
/**
* Тип для mock сервера
*/
export type MockServer = ReturnType<typeof createMockServer>;