feat(auth): create register api call with basic test coverage and msw mock

This commit is contained in:
Ilia Mashkov
2026-03-17 10:08:38 +03:00
parent 701dc981d2
commit 2f863bc5ba
6 changed files with 76 additions and 0 deletions

View File

@@ -1 +1,2 @@
export * from "./login"; export * from "./login";
export * from "./register";

View File

@@ -0,0 +1,6 @@
export const REGISTER_API_ROUTE = "auth/register";
// MOCKS
export const MOCK_EMAIL = "test@test.com";
export const MOCK_PASSWORD = "password";
export const MOCK_TOKEN = "mock.access.token";

View File

@@ -0,0 +1,2 @@
export { register } from "./register";
export { REGISTER_API_ROUTE } from "./constants";

View File

@@ -0,0 +1,25 @@
import { http, HttpResponse } from "msw";
import type { AuthData } from "../../../model/types/service";
import { BASE_URL } from "shared/config";
import { REGISTER_API_ROUTE, MOCK_EMAIL, MOCK_TOKEN } from "./constants";
const REGISTER_URL = `${BASE_URL}/${REGISTER_API_ROUTE}`;
/**
* Msw interceptor. Mocks the register endpoint response.
*/
export const registerMock = http.post(REGISTER_URL, async ({ request }) => {
const { email } = (await request.json()) as AuthData;
if (email === MOCK_EMAIL) {
return HttpResponse.json(
{ message: "User already exists" },
{ status: 409 },
);
}
return HttpResponse.json({
accessToken: MOCK_TOKEN,
user: { id: "2", email },
});
});

View File

@@ -0,0 +1,29 @@
import { setupServer } from "msw/node";
import { register } from "./register";
import { registerMock } from "./register.mock";
import { MOCK_EMAIL, MOCK_PASSWORD, MOCK_TOKEN } from "./constants";
const server = setupServer(registerMock);
describe("register", () => {
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
describe("happy path", () => {
it("returns access token and user for a new email", async () => {
const result = await register({ email: "new@test.com", password: MOCK_PASSWORD });
expect(result.accessToken).toBe(MOCK_TOKEN);
expect(result.user).toEqual({ id: "2", email: "new@test.com" });
});
});
describe("error cases", () => {
it("throws when email is already registered", async () => {
await expect(
register({ email: MOCK_EMAIL, password: MOCK_PASSWORD }),
).rejects.toThrow();
});
});
});

View File

@@ -0,0 +1,13 @@
import { api } from "../../../api";
import type { AuthData, AuthResponse } from "../../../model/types/service";
import { REGISTER_API_ROUTE } from "./constants";
/**
* Registers a new user with the given email and password.
*
* @param registerData - The user's registration data (email and password).
* @returns A promise that resolves to the authentication response.
*/
export function register(registerData: AuthData) {
return api.post(REGISTER_API_ROUTE, { json: registerData }).json<AuthResponse>();
}