Compare commits

21 Commits

Author SHA1 Message Date
6751c7fc04 Merge pull request 'feature/login-and-register-forms' (#2) from feature/login-and-register-forms into main
Reviewed-on: #2
2026-03-24 18:00:41 +00:00
Ilia Mashkov
83fbf83bae feat(RegisterForm): add basic RegisterFormComponent with test coverage and storybook placeholder 2026-03-24 20:57:35 +03:00
Ilia Mashkov
576665f32b test(LoginForm): clarify test case names 2026-03-24 20:42:37 +03:00
Ilia Mashkov
4d854d08a3 test(LoginForm): replace setState with userEvent.type for authenticity 2026-03-24 20:29:16 +03:00
Ilia Mashkov
70bcf7fdcf feat(LoginForm): add isLoading check to LoginForm, add new test cases 2026-03-24 20:03:34 +03:00
Ilia Mashkov
c006a94c4d feat(auth): add selectStatusIsLoading selector to get information whether auth store status equals "loading" 2026-03-24 19:57:27 +03:00
Ilia Mashkov
e4630a7fcb feat(LoginForm): create LoginForm component with basic logic, test coverage and storybook placeholder 2026-03-24 19:30:45 +03:00
Ilia Mashkov
c41f02f505 chore: export modules 2026-03-24 19:29:37 +03:00
Ilia Mashkov
683443673e chore: remove unused code 2026-03-24 19:28:55 +03:00
Ilia Mashkov
1f20f11852 chore: install storybook 2026-03-24 19:28:20 +03:00
Ilia Mashkov
c378f7c83a refactor(auth): rewrite store actions, remove arguments, add checks validation and status checks; add test cases 2026-03-24 13:04:58 +03:00
Ilia Mashkov
8cea93220b feat(auth): create selectors for authStore; cover them with tests 2026-03-24 13:02:58 +03:00
Ilia Mashkov
b871bf27de feat(auth): add formData to the auth store; add corresponding setEmail and setPassword actions 2026-03-24 11:15:23 +03:00
db42c87489 Merge pull request 'feature/state-and-data-fetching' (#1) from feature/state-and-data-fetching into main
Reviewed-on: #1
2026-03-24 08:02:19 +00:00
Ilia Mashkov
6a2a826a11 refactor: create separate shared store for auth token and refresh action 2026-03-24 09:26:10 +03:00
Ilia Mashkov
fd5b50a6f2 test(auth): write basic unit tests for authStore actions 2026-03-18 09:58:30 +03:00
Ilia Mashkov
51fc64d8c3 feat(auth): add accessToken field to the store 2026-03-18 09:57:59 +03:00
Ilia Mashkov
2afbd73a31 fix(auth): fix circular import problem by changing the way the authHttpClient gets accessToken; replace individual calls mocks with the common ones 2026-03-18 09:10:17 +03:00
Ilia Mashkov
b75e805f54 feat(auth): add refresh action to authStore 2026-03-17 14:18:49 +03:00
Ilia Mashkov
226874bbec feat(auth): add refresh api call call 2026-03-17 14:15:32 +03:00
Ilia Mashkov
ed718eea71 feat(auth): add accessToken field to authStore and setup beforeRequest hook to add this token to headers 2026-03-17 14:08:29 +03:00
55 changed files with 1981 additions and 126 deletions

View File

@@ -1,3 +1,6 @@
// For more info, see https://github.com/storybookjs/eslint-plugin-storybook#configuration-flat-config-format
import storybook from "eslint-plugin-storybook";
import js from '@eslint/js' import js from '@eslint/js'
import globals from 'globals' import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks' import reactHooks from 'eslint-plugin-react-hooks'
@@ -5,9 +8,7 @@ import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint' import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config' import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([ export default defineConfig([globalIgnores(['dist']), {
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'], files: ['**/*.{ts,tsx}'],
extends: [ extends: [
js.configs.recommended, js.configs.recommended,
@@ -19,5 +20,4 @@ export default defineConfig([
ecmaVersion: 2020, ecmaVersion: 2020,
globals: globals.browser, globals: globals.browser,
}, },
}, }, ...storybook.configs["flat/recommended"]])
])

View File

@@ -10,7 +10,9 @@
"preview": "vite preview", "preview": "vite preview",
"test:unit": "vitest", "test:unit": "vitest",
"test:run": "vitest run", "test:run": "vitest run",
"test:coverage": "vitest run --coverage" "test:coverage": "vitest run --coverage",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
}, },
"dependencies": { "dependencies": {
"ky": "^1.14.3", "ky": "^1.14.3",
@@ -19,8 +21,13 @@
"zustand": "^5.0.12" "zustand": "^5.0.12"
}, },
"devDependencies": { "devDependencies": {
"@chromatic-com/storybook": "^5.0.2",
"@eslint/js": "^9.39.1", "@eslint/js": "^9.39.1",
"@module-federation/vite": "^1.12.3", "@module-federation/vite": "^1.12.3",
"@storybook/addon-a11y": "^10.3.3",
"@storybook/addon-docs": "^10.3.3",
"@storybook/addon-vitest": "^10.3.3",
"@storybook/react-vite": "^10.3.3",
"@testing-library/dom": "^10.4.1", "@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1", "@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2", "@testing-library/react": "^16.3.2",
@@ -29,14 +36,18 @@
"@types/react": "^19.2.7", "@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.4", "@vitejs/plugin-react": "^5.1.4",
"@vitest/browser-playwright": "4.1.0",
"@vitest/coverage-v8": "^4.1.0", "@vitest/coverage-v8": "^4.1.0",
"babel-plugin-react-compiler": "^1.0.0", "babel-plugin-react-compiler": "^1.0.0",
"eslint": "^9.39.1", "eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24", "eslint-plugin-react-refresh": "^0.4.24",
"eslint-plugin-storybook": "^10.3.3",
"globals": "^16.5.0", "globals": "^16.5.0",
"jsdom": "^29.0.0", "jsdom": "^29.0.0",
"msw": "^2.12.11", "msw": "^2.12.11",
"playwright": "^1.58.2",
"storybook": "^10.3.3",
"typescript": "~5.9.3", "typescript": "~5.9.3",
"typescript-eslint": "^8.48.0", "typescript-eslint": "^8.48.0",
"vite": "^7.3.1", "vite": "^7.3.1",

View File

@@ -1,3 +1,4 @@
export * from "./login"; export * from "./login";
export * from "./register"; export * from "./register";
export * from "./logout"; export * from "./logout";
export * from "./mocks";

View File

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

View File

@@ -1,2 +1,2 @@
export { login } from './login'; export { login } from "./login";
export { LOGIN_API_ROUTE } from './constants'; export { loginMock } from "./login.mock";

View File

@@ -1,12 +1,8 @@
import { http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import type { AuthData } from "../../../model/types/service"; import type { AuthData } from "../../../model/types/service";
import { BASE_URL } from "shared/config"; import { BASE_URL } from "shared/api";
import { import { LOGIN_API_ROUTE } from "./login";
LOGIN_API_ROUTE, import { MOCK_AUTH_RESPONSE, MOCK_EMAIL, MOCK_PASSWORD } from "../mocks";
MOCK_EMAIL,
MOCK_PASSWORD,
MOCK_TOKEN,
} from "./constants";
const LOGIN_URL = `${BASE_URL}/${LOGIN_API_ROUTE}`; const LOGIN_URL = `${BASE_URL}/${LOGIN_API_ROUTE}`;
@@ -17,10 +13,7 @@ export const loginMock = http.post(LOGIN_URL, async ({ request }) => {
const { email, password } = (await request.json()) as AuthData; const { email, password } = (await request.json()) as AuthData;
if (email === MOCK_EMAIL && password === MOCK_PASSWORD) { if (email === MOCK_EMAIL && password === MOCK_PASSWORD) {
return HttpResponse.json({ return HttpResponse.json(MOCK_AUTH_RESPONSE);
accessToken: MOCK_TOKEN,
user: { id: "1", email },
});
} }
return HttpResponse.json({ message: "Invalid credentials" }, { status: 401 }); return HttpResponse.json({ message: "Invalid credentials" }, { status: 401 });

View File

@@ -1,7 +1,8 @@
import { setupServer } from "msw/node"; import { setupServer } from "msw/node";
import { login } from "./login"; import { login } from "./login";
import { loginMock } from "./login.mock"; import { loginMock } from "./login.mock";
import { MOCK_EMAIL, MOCK_PASSWORD } from "./constants"; import { MOCK_EMAIL, MOCK_EXISTING_USER, MOCK_PASSWORD } from "../mocks";
import { MOCK_TOKEN } from "shared/api";
const server = setupServer(loginMock); const server = setupServer(loginMock);
@@ -12,10 +13,13 @@ describe("login", () => {
describe("happy path", () => { describe("happy path", () => {
it("returns access token and user on valid credentials", async () => { it("returns access token and user on valid credentials", async () => {
const result = await login({ email: MOCK_EMAIL, password: MOCK_PASSWORD }); const result = await login({
email: MOCK_EMAIL,
password: MOCK_PASSWORD,
});
expect(result.accessToken).toBe("mock.access.token"); expect(result.accessToken).toBe(MOCK_TOKEN);
expect(result.user).toEqual({ id: "1", email: MOCK_EMAIL }); expect(result.user).toEqual(MOCK_EXISTING_USER);
}); });
}); });

View File

@@ -1,6 +1,7 @@
import { api } from "../../../api";
import type { AuthData, AuthResponse } from "../../../model/types/service"; import type { AuthData, AuthResponse } from "../../../model/types/service";
import { LOGIN_API_ROUTE } from "./constants"; import { authHttpClient } from "../../config/authApi/authApi";
export const LOGIN_API_ROUTE = "auth/login";
/** /**
* Logs in a user with the given email and password. * Logs in a user with the given email and password.
@@ -9,5 +10,7 @@ import { LOGIN_API_ROUTE } from "./constants";
* @returns A promise that resolves to the authentication response. * @returns A promise that resolves to the authentication response.
*/ */
export function login(loginData: AuthData) { export function login(loginData: AuthData) {
return api.post(LOGIN_API_ROUTE, { json: loginData }).json<AuthResponse>(); return authHttpClient
.post(LOGIN_API_ROUTE, { json: loginData })
.json<AuthResponse>();
} }

View File

@@ -1 +0,0 @@
export const LOGOUT_API_ROUTE = "auth/logout";

View File

@@ -1,2 +1,2 @@
export { logout } from "./logout"; export { logout } from "./logout";
export { LOGOUT_API_ROUTE } from "./constants"; export { logoutMock } from "./logout.mock";

View File

@@ -1,6 +1,6 @@
import { http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import { BASE_URL } from "shared/config"; import { BASE_URL } from "shared/api";
import { LOGOUT_API_ROUTE } from "./constants"; import { LOGOUT_API_ROUTE } from "./logout";
const LOGOUT_URL = `${BASE_URL}/${LOGOUT_API_ROUTE}`; const LOGOUT_URL = `${BASE_URL}/${LOGOUT_API_ROUTE}`;

View File

@@ -1,5 +1,6 @@
import { api } from "../../../api"; import { authHttpClient } from "../../config";
import { LOGOUT_API_ROUTE } from "./constants";
export const LOGOUT_API_ROUTE = "auth/logout";
/** /**
* Logs out the currently authenticated user. * Logs out the currently authenticated user.
@@ -8,5 +9,5 @@ import { LOGOUT_API_ROUTE } from "./constants";
* @returns A promise that resolves when the session is terminated. * @returns A promise that resolves when the session is terminated.
*/ */
export async function logout(): Promise<void> { export async function logout(): Promise<void> {
await api.post(LOGOUT_API_ROUTE); await authHttpClient.post(LOGOUT_API_ROUTE);
} }

View File

@@ -0,0 +1,22 @@
import type { User } from "entities/User";
import type { AuthResponse } from "../../model";
import { MOCK_TOKEN } from "shared/api";
export const MOCK_EMAIL = "test@test.com";
export const MOCK_NEW_EMAIL = "new@test.com";
export const MOCK_PASSWORD = "password";
export const MOCK_EXISTING_USER: User = {
id: "1",
email: MOCK_EMAIL,
};
export const MOCK_NEW_USER: User = {
id: "2",
email: MOCK_NEW_EMAIL,
};
export const MOCK_AUTH_RESPONSE: AuthResponse = {
accessToken: MOCK_TOKEN,
user: MOCK_EXISTING_USER,
};

View File

@@ -1,6 +0,0 @@
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

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

View File

@@ -1,7 +1,8 @@
import { http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import type { AuthData } from "../../../model/types/service"; import type { AuthData } from "../../../model/types/service";
import { BASE_URL } from "shared/config"; import { BASE_URL, MOCK_TOKEN } from "shared/api";
import { REGISTER_API_ROUTE, MOCK_EMAIL, MOCK_TOKEN } from "./constants"; import { REGISTER_API_ROUTE } from "./register";
import { MOCK_EMAIL } from "../mocks";
const REGISTER_URL = `${BASE_URL}/${REGISTER_API_ROUTE}`; const REGISTER_URL = `${BASE_URL}/${REGISTER_API_ROUTE}`;

View File

@@ -1,7 +1,13 @@
import { setupServer } from "msw/node"; import { setupServer } from "msw/node";
import { register } from "./register"; import { register } from "./register";
import { registerMock } from "./register.mock"; import { registerMock } from "./register.mock";
import { MOCK_EMAIL, MOCK_PASSWORD, MOCK_TOKEN } from "./constants"; import {
MOCK_EMAIL,
MOCK_NEW_EMAIL,
MOCK_NEW_USER,
MOCK_PASSWORD,
} from "../mocks";
import { MOCK_TOKEN } from "shared/api";
const server = setupServer(registerMock); const server = setupServer(registerMock);
@@ -12,10 +18,13 @@ describe("register", () => {
describe("happy path", () => { describe("happy path", () => {
it("returns access token and user for a new email", async () => { it("returns access token and user for a new email", async () => {
const result = await register({ email: "new@test.com", password: MOCK_PASSWORD }); const result = await register({
email: MOCK_NEW_EMAIL,
password: MOCK_PASSWORD,
});
expect(result.accessToken).toBe(MOCK_TOKEN); expect(result.accessToken).toBe(MOCK_TOKEN);
expect(result.user).toEqual({ id: "2", email: "new@test.com" }); expect(result.user).toEqual(MOCK_NEW_USER);
}); });
}); });

View File

@@ -1,6 +1,7 @@
import { api } from "../../../api";
import type { AuthData, AuthResponse } from "../../../model/types/service"; import type { AuthData, AuthResponse } from "../../../model/types/service";
import { REGISTER_API_ROUTE } from "./constants"; import { authHttpClient } from "../../config/authApi/authApi";
export const REGISTER_API_ROUTE = "auth/register";
/** /**
* Registers a new user with the given email and password. * Registers a new user with the given email and password.
@@ -9,5 +10,7 @@ import { REGISTER_API_ROUTE } from "./constants";
* @returns A promise that resolves to the authentication response. * @returns A promise that resolves to the authentication response.
*/ */
export function register(registerData: AuthData) { export function register(registerData: AuthData) {
return api.post(REGISTER_API_ROUTE, { json: registerData }).json<AuthResponse>(); return authHttpClient
.post(REGISTER_API_ROUTE, { json: registerData })
.json<AuthResponse>();
} }

View File

@@ -1,18 +1,33 @@
import { api as baseApi } from "shared/config"; import { api as baseApi, useTokenStore } from "shared/api";
// Extend base API with authentication hooks export const authHttpClient = baseApi.extend({
export const api = baseApi.extend({
hooks: { hooks: {
beforeRequest: [ beforeRequest: [
(request) => { (request) => {
// Add authentication token to request headers const token = useTokenStore.getState().accessToken;
if (token) {
request.headers.set("Authorization", `Bearer ${token}`);
}
return request; return request;
}, },
], ],
afterResponse: [ afterResponse: [
async (request, options, response) => { async (request, options, response) => {
// Refresh token logic if (response.status !== 401) {
return response; return response;
}
const { accessToken, refreshToken } = useTokenStore.getState();
if (!accessToken) return response;
try {
await refreshToken?.();
return authHttpClient(request); // beforeRequest picks up new token automatically
} catch {
return response;
}
}, },
], ],
}, },

View File

@@ -1 +1 @@
export * from "./authApi/authApi"; export { authHttpClient } from "./authApi/authApi";

View File

@@ -3,4 +3,7 @@ export * from "./types/service";
export * from "./types/store"; export * from "./types/store";
// Stores // Stores
export * from "./stores/authStore/authStore"; export * from "./stores";
// Selectors
export * from "./selectors";

View File

@@ -0,0 +1,3 @@
export * from "./selectFormValid/selectFormValid";
export * from "./selectAuthData/selectAuthData";
export * from "./selectStatusIsLoading/selectStatusIsLoading";

View File

@@ -0,0 +1,14 @@
import { useAuthStore } from "../../stores/authStore/authStore";
import { selectAuthData } from "./selectAuthData";
import { MOCK_EMAIL, MOCK_PASSWORD } from "../../../api/calls/mocks";
describe("selectAuthData", () => {
it("should return the correct auth data", () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
expect(selectAuthData(useAuthStore.getState())).toEqual({
email: MOCK_EMAIL,
password: MOCK_PASSWORD,
});
});
});

View File

@@ -0,0 +1,7 @@
import type { AuthData } from "../../types/service";
import type { AuthStore } from "../../types/store";
export const selectAuthData = (state: AuthStore): AuthData => ({
email: state.formData.email.value,
password: state.formData.password.value,
});

View File

@@ -0,0 +1,25 @@
import { MOCK_EMAIL, MOCK_PASSWORD } from "../../../api/calls/mocks";
import { useAuthStore } from "../../stores/authStore/authStore";
import { selectFormValid } from "./selectFormValid";
describe("selectFormValid", () => {
afterEach(() => {
useAuthStore.getState().reset();
});
it("should be false when email is invalid", () => {
useAuthStore.getState().setEmail("");
expect(selectFormValid(useAuthStore.getState())).toBe(false);
});
it("should be false when password is invalid", () => {
useAuthStore.getState().setPassword("");
expect(selectFormValid(useAuthStore.getState())).toBe(false);
});
it("should be true when email and password are valid", () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
expect(selectFormValid(useAuthStore.getState())).toBe(true);
});
});

View File

@@ -0,0 +1,4 @@
import type { AuthStore } from "../../types/store";
export const selectFormValid = (state: AuthStore) =>
Object.values(state.formData).every((field) => field.valid);

View File

@@ -0,0 +1,18 @@
import { useAuthStore } from "../../stores";
import { selectStatusIsLoading } from "./selectStatusIsLoading";
describe("selectStatusIsLoading", () => {
afterEach(() => {
useAuthStore.getState().reset();
});
it("should return true when status is 'loading'", () => {
useAuthStore.setState({ status: "loading" });
expect(selectStatusIsLoading(useAuthStore.getState())).toBe(true);
});
it("should return false when status is not 'loading'", () => {
useAuthStore.setState({ status: "idle" });
expect(selectStatusIsLoading(useAuthStore.getState())).toBe(false);
});
});

View File

@@ -0,0 +1,4 @@
import type { AuthStore } from "../../types/store";
export const selectStatusIsLoading = (state: AuthStore) =>
state.status === "loading";

View File

@@ -0,0 +1,170 @@
import { setupServer } from "msw/node";
import * as apiCalls from "../../../api/calls";
import { defaultStoreState, useAuthStore } from "./authStore";
import {
MOCK_EMAIL,
MOCK_NEW_EMAIL,
MOCK_PASSWORD,
} from "../../../api/calls/mocks";
const server = setupServer(
apiCalls.loginMock,
apiCalls.registerMock,
apiCalls.logoutMock,
);
const loginSpy = vi.spyOn(apiCalls, "login");
const registerSpy = vi.spyOn(apiCalls, "register");
const logoutSpy = vi.spyOn(apiCalls, "logout");
describe("authStore", () => {
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => {
useAuthStore.getState().reset();
server.resetHandlers();
});
afterAll(() => server.close());
describe("setEmail", () => {
it("should set the email in formData", () => {
useAuthStore.getState().setEmail(MOCK_NEW_EMAIL);
expect(useAuthStore.getState().formData.email).toMatchObject({
value: MOCK_NEW_EMAIL,
});
});
});
describe("setPassword", () => {
it("should set the password in formData", () => {
useAuthStore.getState().setPassword(MOCK_PASSWORD);
expect(useAuthStore.getState().formData.password).toMatchObject({
value: MOCK_PASSWORD,
});
});
});
describe("reset", () => {
it("should reset the store to default state", () => {
useAuthStore.getState().reset();
expect(useAuthStore.getState()).toMatchObject(defaultStoreState);
});
});
describe("login", () => {
it("should not do api call if status is loading", async () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
useAuthStore.setState({ status: "loading" });
await useAuthStore.getState().login();
expect(loginSpy).not.toHaveBeenCalled();
});
it("should not do api call if form is invalid", async () => {
useAuthStore.getState().setEmail("");
useAuthStore.getState().setPassword("");
await useAuthStore.getState().login();
const { status } = useAuthStore.getState();
expect(loginSpy).not.toHaveBeenCalled();
expect(status).toBe("idle");
});
it("should set access token, user data, and update status after successful login", async () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
await useAuthStore.getState().login();
const { user, status, error } = useAuthStore.getState();
expect(user).toBeDefined();
expect(status).toBe("authenticated");
expect(error).toBeNull();
});
it("should set error and update status if login fails", async () => {
useAuthStore.getState().setEmail("wrong@test.com");
useAuthStore.getState().setPassword("wrongPassword");
await useAuthStore.getState().login();
const { status, error } = useAuthStore.getState();
expect(status).toBe("unauthenticated");
expect(error).toBeDefined();
});
});
describe("register", () => {
it("should not do api call if status is loading", async () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
useAuthStore.setState({ status: "loading" });
await useAuthStore.getState().register();
expect(registerSpy).not.toHaveBeenCalled();
});
it("should not do api call if form is invalid", async () => {
useAuthStore.getState().setEmail("");
useAuthStore.getState().setPassword("");
await useAuthStore.getState().register();
const { status } = useAuthStore.getState();
expect(registerSpy).not.toHaveBeenCalled();
expect(status).toBe("idle");
});
it("should set access token, user data, and update status after successful registration", async () => {
useAuthStore.getState().setEmail(MOCK_NEW_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
await useAuthStore.getState().register();
const { user, status, error } = useAuthStore.getState();
expect(user).toBeDefined();
expect(status).toBe("authenticated");
expect(error).toBeNull();
});
it("should set error and update status if registration fails", async () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
await useAuthStore.getState().register();
const { status, error } = useAuthStore.getState();
expect(status).toBe("unauthenticated");
expect(error).toBeDefined();
});
});
describe("logout", () => {
it("should not do api call if status is loading", async () => {
useAuthStore.setState({ status: "loading" });
await useAuthStore.getState().logout();
expect(logoutSpy).not.toHaveBeenCalled();
});
it("should clear access token, user data, and update status after logout", async () => {
await useAuthStore.getState().logout();
const { user, status, error } = useAuthStore.getState();
expect(user).toBeUndefined();
expect(status).toBe("unauthenticated");
expect(error).toBeNull();
});
});
});

View File

@@ -1,17 +1,68 @@
import { create } from "zustand"; import { create } from "zustand";
import type { AuthStore } from "../../types/store"; import type { AuthStore, AuthStoreState } from "../../types/store";
import { login, logout, register } from "../../../api"; import { login, logout, register } from "../../../api";
import { callApi } from "shared/utils"; import { callApi } from "shared/utils";
import { UNEXPECTED_ERROR_MESSAGE } from "shared/config"; import { UNEXPECTED_ERROR_MESSAGE } from "shared/api";
import { selectAuthData, selectFormValid } from "../../selectors";
export const useAuthStore = create<AuthStore>()((set) => ({ export const defaultStoreState: Readonly<AuthStoreState> = {
formData: {
email: { value: "", valid: false },
password: { value: "", valid: false },
},
user: undefined, user: undefined,
status: "idle", status: "idle",
error: null, error: null,
};
function validateEmail(email: string): boolean {
return Boolean(email);
}
function validatePassword(password: string): boolean {
return Boolean(password);
}
export const useAuthStore = create<AuthStore>()((set, get) => ({
...defaultStoreState,
setEmail: (email: string) => {
const isValid = validateEmail(email);
set((state) => ({
formData: { ...state.formData, email: { value: email, valid: isValid } },
}));
},
setPassword: (password: string) => {
const isValid = validatePassword(password);
set((state) => ({
formData: {
...state.formData,
password: { value: password, valid: isValid },
},
}));
},
reset: () => {
set(defaultStoreState);
},
login: async () => {
const { status } = get();
if (status === "loading") {
return;
}
login: async (loginData) => {
set({ status: "loading" }); set({ status: "loading" });
const formValid = selectFormValid(get());
if (!formValid) {
set({ status: "idle" });
return;
}
try { try {
const loginData = selectAuthData(get());
const [responseData, loginError] = await callApi(() => login(loginData)); const [responseData, loginError] = await callApi(() => login(loginData));
if (loginError) { if (loginError) {
@@ -32,8 +83,24 @@ export const useAuthStore = create<AuthStore>()((set) => ({
}); });
} }
}, },
register: async (registerData) => { register: async () => {
const { status } = get();
if (status === "loading") {
return;
}
set({ status: "loading" });
const formValid = selectFormValid(get());
if (!formValid) {
set({ status: "idle" });
return;
}
try { try {
const registerData = selectAuthData(get());
const [responseData, registerError] = await callApi(() => const [responseData, registerError] = await callApi(() =>
register(registerData), register(registerData),
); );
@@ -57,12 +124,18 @@ export const useAuthStore = create<AuthStore>()((set) => ({
} }
}, },
logout: async () => { logout: async () => {
const prevStatus = get().status;
if (prevStatus === "loading") {
return;
}
set({ status: "loading" }); set({ status: "loading" });
try { try {
const [, logoutError] = await callApi(() => logout()); const [, logoutError] = await callApi(() => logout());
if (logoutError) { if (logoutError) {
set({ error: logoutError }); set({ error: logoutError, status: prevStatus });
return; return;
} }
@@ -71,6 +144,8 @@ export const useAuthStore = create<AuthStore>()((set) => ({
user: undefined, user: undefined,
error: null, error: null,
}); });
// useTokenStore.setState({ accessToken: null });
} catch (err) { } catch (err) {
console.error(err); console.error(err);
set({ error: new Error(UNEXPECTED_ERROR_MESSAGE) }); set({ error: new Error(UNEXPECTED_ERROR_MESSAGE) });

View File

@@ -0,0 +1 @@
export { useAuthStore } from "./authStore/authStore";

View File

@@ -2,9 +2,20 @@ import type { User } from "entities/User";
import type { AuthData, AuthStatus } from "./service"; import type { AuthData, AuthStatus } from "./service";
import type { ApiError } from "shared/utils"; import type { ApiError } from "shared/utils";
export type AuthFormData = {
[K in keyof AuthData]: {
value: AuthData[K];
valid: boolean;
};
};
export interface AuthStoreState { export interface AuthStoreState {
/** /**
* User's credentials * Form data for login/register forms
*/
formData: AuthFormData;
/**
* Current user
*/ */
user?: User; user?: User;
/** /**
@@ -17,15 +28,14 @@ export interface AuthStoreState {
error: ApiError | Error | null; error: ApiError | Error | null;
} }
export type LoginAction = (data: AuthData) => void;
export type RegisterAction = (data: AuthData) => void;
export type LogoutAction = () => void;
export interface AuthStoreActions { export interface AuthStoreActions {
// Async actions setEmail: (email: string) => void;
login: LoginAction; setPassword: (password: string) => void;
register: RegisterAction; reset: () => void;
logout: LogoutAction;
login: () => Promise<void>;
register: () => Promise<void>;
logout: () => Promise<void>;
} }
export type AuthStore = AuthStoreState & AuthStoreActions; export type AuthStore = AuthStoreState & AuthStoreActions;

View File

@@ -0,0 +1,89 @@
import { selectAuthData, useAuthStore } from "../../model";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { LoginForm } from "./LoginForm";
import { MOCK_EMAIL, MOCK_PASSWORD } from "../../api";
describe("LoginForm", () => {
afterEach(() => {
useAuthStore.getState().reset();
vi.restoreAllMocks();
});
it("should render form", () => {
render(<LoginForm />);
const form = screen.getByRole("form");
expect(form).toBeInTheDocument();
});
it("disables submit button when form is invalid", () => {
render(<LoginForm />);
const loginButton = screen.getByRole("button", { name: /login/i });
expect(loginButton).toBeDisabled();
});
it("disables submit button when auth store status equals loading", async () => {
useAuthStore.setState({ status: "loading" });
render(<LoginForm />);
const emailInput = screen.getByRole("textbox", { name: /email/i });
const passwordInput = screen.getByLabelText(/password/i);
const loginButton = screen.getByRole("button", { name: /login/i });
await userEvent.type(emailInput, MOCK_EMAIL);
await userEvent.type(passwordInput, MOCK_PASSWORD);
expect(loginButton).toBeDisabled();
});
it("enables submit button when form is valid and auth store status isn't equal to loading", async () => {
useAuthStore.setState({ status: "idle" });
render(<LoginForm />);
const emailInput = screen.getByRole("textbox", { name: /email/i });
const passwordInput = screen.getByLabelText(/password/i);
const loginButton = screen.getByRole("button", { name: /login/i });
await userEvent.type(emailInput, MOCK_EMAIL);
await userEvent.type(passwordInput, MOCK_PASSWORD);
expect(loginButton).toBeEnabled();
});
it("updates email value in auth store when user types", async () => {
render(<LoginForm />);
const emailInput = screen.getByRole("textbox", { name: /email/i });
await userEvent.type(emailInput, MOCK_EMAIL);
const storeEmailValue = selectAuthData(useAuthStore.getState()).email;
expect(storeEmailValue).toBe(MOCK_EMAIL);
});
it("updates password value in auth store when user types", async () => {
render(<LoginForm />);
const passwordInput = screen.getByLabelText(/password/i);
await userEvent.type(passwordInput, MOCK_PASSWORD);
const storePasswordValue = selectAuthData(useAuthStore.getState()).password;
expect(storePasswordValue).toBe(MOCK_PASSWORD);
});
it("calls login when submit form is valid and user clicks submit", async () => {
const loginSpy = vi.spyOn(useAuthStore.getState(), "login");
useAuthStore.setState({ status: "idle" });
render(<LoginForm />);
const emailInput = screen.getByRole("textbox", { name: /email/i });
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole("button", { name: /login/i });
await userEvent.type(emailInput, MOCK_EMAIL);
await userEvent.type(passwordInput, MOCK_PASSWORD);
await userEvent.click(submitButton);
expect(loginSpy).toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,12 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { LoginForm } from "./LoginForm";
const meta: Meta<typeof LoginForm> = {
component: LoginForm,
title: "features/auth/LoginForm",
};
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {};

View File

@@ -1,5 +1,51 @@
import {
selectFormValid,
selectStatusIsLoading,
useAuthStore,
} from "../../model";
import type { SubmitEvent, ChangeEvent } from "react";
/**
* Login form component
*/
export function LoginForm() { export function LoginForm() {
const { formData, setEmail, setPassword, login } = useAuthStore();
const formValid = useAuthStore(selectFormValid);
const isLoading = useAuthStore(selectStatusIsLoading);
const disabled = !formValid || isLoading;
const handleEmailChange = (e: ChangeEvent<HTMLInputElement>) => {
setEmail(e.target.value);
};
const handlePasswordChange = (e: ChangeEvent<HTMLInputElement>) => {
setPassword(e.target.value);
};
const handleSubmit = (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
login();
};
return ( return (
<form>Login Form</form> <form aria-label="Login form" onSubmit={handleSubmit}>
<input
type="email"
aria-label="Email"
value={formData?.email?.value ?? ""}
onChange={handleEmailChange}
/>
<input
type="password"
aria-label="Password"
value={formData?.password?.value ?? ""}
onChange={handlePasswordChange}
/>
<button type="submit" disabled={disabled}>
Login
</button>
</form>
); );
} }

View File

@@ -0,0 +1,115 @@
import { render, screen } from "@testing-library/react";
import { RegisterForm } from "./RegisterForm";
import { selectAuthData, useAuthStore } from "../../model";
import { MOCK_NEW_EMAIL, MOCK_PASSWORD } from "../../api";
import userEvent from "@testing-library/user-event";
describe("RegisterForm", () => {
afterEach(() => {
useAuthStore.getState().reset();
vi.restoreAllMocks();
});
it("should render form", () => {
render(<RegisterForm />);
const form = screen.getByRole("form");
expect(form).toBeInTheDocument();
});
it("should disable button when form is invalid", async () => {
render(<RegisterForm />);
const registerButton = screen.getByRole("button", { name: /register/i });
expect(registerButton).toBeDisabled();
});
it("should disable button when auth store status equals loading", async () => {
useAuthStore.setState({ status: "loading" });
render(<RegisterForm />);
const emailInput = screen.getByRole("textbox", { name: /email/i });
const passwordInput = screen.getByLabelText(/password/i);
const confirmPasswordInput = screen.getByLabelText(/confirm/i);
const registerButton = screen.getByRole("button", { name: /register/i });
await userEvent.type(emailInput, MOCK_NEW_EMAIL);
await userEvent.type(passwordInput, MOCK_PASSWORD);
await userEvent.type(confirmPasswordInput, MOCK_PASSWORD);
expect(registerButton).toBeDisabled();
});
it("should disable button when password and confirm password do not match", async () => {
render(<RegisterForm />);
const emailInput = screen.getByRole("textbox", { name: /email/i });
const passwordInput = screen.getByLabelText(/password/i);
const confirmPasswordInput = screen.getByLabelText(/confirm/i);
const registerButton = screen.getByRole("button", { name: /register/i });
await userEvent.type(emailInput, MOCK_NEW_EMAIL);
await userEvent.type(passwordInput, MOCK_PASSWORD);
await userEvent.type(confirmPasswordInput, MOCK_PASSWORD + "1");
expect(registerButton).toBeDisabled();
});
it("should enable button when password and confirm password match and auth store status isn't equal to loading", async () => {
useAuthStore.setState({ status: "idle" });
render(<RegisterForm />);
const emailInput = screen.getByRole("textbox", { name: /email/i });
const passwordInput = screen.getByLabelText(/password/i);
const confirmPasswordInput = screen.getByLabelText(/confirm/i);
const registerButton = screen.getByRole("button", { name: /register/i });
await userEvent.type(emailInput, MOCK_NEW_EMAIL);
await userEvent.type(passwordInput, MOCK_PASSWORD);
await userEvent.type(confirmPasswordInput, MOCK_PASSWORD);
expect(registerButton).not.toBeDisabled();
});
it("should change email value in auth store when user types", async () => {
render(<RegisterForm />);
const emailInput = screen.getByRole("textbox", { name: /email/i });
await userEvent.type(emailInput, MOCK_NEW_EMAIL);
const storeEmailValue = selectAuthData(useAuthStore.getState()).email;
expect(storeEmailValue).toBe(MOCK_NEW_EMAIL);
});
it("should change password value in auth store when user types", async () => {
render(<RegisterForm />);
const passwordInput = screen.getByLabelText(/password/i);
await userEvent.type(passwordInput, MOCK_PASSWORD);
const storePasswordValue = selectAuthData(useAuthStore.getState()).password;
expect(storePasswordValue).toBe(MOCK_PASSWORD);
});
it("should perform register api call when user clicks register button", async () => {
const registerSpy = vi.spyOn(useAuthStore.getState(), "register");
useAuthStore.setState({ status: "idle" });
render(<RegisterForm />);
const emailInput = screen.getByRole("textbox", { name: /email/i });
const passwordInput = screen.getByLabelText(/password/i);
const confirmPasswordInput = screen.getByLabelText(/confirm/i);
const registerButton = screen.getByRole("button", { name: /register/i });
await userEvent.type(emailInput, MOCK_NEW_EMAIL);
await userEvent.type(passwordInput, MOCK_PASSWORD);
await userEvent.type(confirmPasswordInput, MOCK_PASSWORD);
await userEvent.click(registerButton);
expect(registerSpy).toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,12 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { RegisterForm } from "./RegisterForm";
const meta: Meta<typeof RegisterForm> = {
component: RegisterForm,
title: "features/auth/RegisterForm",
};
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {};

View File

@@ -1,5 +1,64 @@
import { useState, type ChangeEvent, type SubmitEvent } from "react";
import {
selectFormValid,
selectStatusIsLoading,
useAuthStore,
} from "../../model";
/**
* Register form component
*/
export function RegisterForm() { export function RegisterForm() {
const { formData, setEmail, setPassword, register } = useAuthStore();
const [confirmedPassword, setConfirmedPassword] = useState("");
const formValid = useAuthStore(selectFormValid);
const isLoading = useAuthStore(selectStatusIsLoading);
const passwordMatch = formData?.password?.value === confirmedPassword;
const disabled = isLoading || !formValid || !passwordMatch;
const handleEmailChange = (e: ChangeEvent<HTMLInputElement>) => {
setEmail(e.target.value);
};
const handlePasswordChange = (e: ChangeEvent<HTMLInputElement>) => {
setPassword(e.target.value);
};
const handleConfirmChange = (e: ChangeEvent<HTMLInputElement>) => {
setConfirmedPassword(e.target.value);
};
const handleSubmit = (e: SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
register();
};
return ( return (
<form>Register Form</form> <form aria-label="Register Form" onSubmit={handleSubmit}>
<input
type="email"
aria-label="Email"
value={formData?.email?.value ?? ""}
onChange={handleEmailChange}
/>
<input
type="password"
aria-label="Password"
value={formData?.password?.value ?? ""}
onChange={handlePasswordChange}
/>
<input
type="password"
aria-label="Confirm"
value={confirmedPassword}
onChange={handleConfirmChange}
/>
<button type="submit" aria-label="Register" disabled={disabled}>
Register
</button>
</form>
); );
} }

View File

@@ -0,0 +1,2 @@
export * from "./refresh/refresh";
export * from "./refresh/refresh.mock";

View File

@@ -0,0 +1,2 @@
export { refresh } from "./refresh";
export { refreshMock } from "./refresh.mock";

View File

@@ -0,0 +1,26 @@
import { http, HttpResponse } from "msw";
import { REFRESH_API_ROUTE } from "./refresh";
import { BASE_URL, MOCK_FRESH_TOKEN, MOCK_TOKEN } from "../../model";
const REFRESH_URL = `${BASE_URL}/${REFRESH_API_ROUTE}`;
const MOCK_BEARER_TOKEN = `Bearer ${MOCK_TOKEN}`;
/**
* Msw interceptor. Mocks the refresh endpoint response.
* Cookie validation is a server concern — always returns a fresh token.
* Use server.use() to override with a 401 in tests that need a failure case.
*/
export const refreshMock = http.post(REFRESH_URL, async ({ request }) => {
if (request.headers.get("Authorization") === MOCK_BEARER_TOKEN) {
return HttpResponse.json({
accessToken: MOCK_FRESH_TOKEN,
});
}
return HttpResponse.json(
{
error: "Unauthorized",
},
{ status: 401 },
);
});

View File

@@ -0,0 +1,30 @@
import { setupServer } from "msw/node";
import { useTokenStore } from "../../model/stores/tokenStore";
import { refresh } from "./refresh";
import { refreshMock } from "./refresh.mock";
import { MOCK_FRESH_TOKEN, MOCK_TOKEN } from "../../model/const";
const server = setupServer(refreshMock);
describe("refresh", () => {
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => {
server.resetHandlers();
useTokenStore.setState({ accessToken: undefined });
});
afterAll(() => server.close());
describe("happy path", () => {
it("returns a fresh access token and user when session is valid", async () => {
const result = await refresh(MOCK_TOKEN);
expect(result.accessToken).toBe(MOCK_FRESH_TOKEN);
});
});
describe("error cases", () => {
it("throws when session is expired or missing", async () => {
await expect(refresh("expired_token")).rejects.toThrow();
});
});
});

View File

@@ -0,0 +1,10 @@
import { api } from "../../config/api";
import type { RefreshTokenResponse } from "../../model/types";
export const REFRESH_API_ROUTE = "auth/refresh";
export function refresh(token: string) {
return api
.post(REFRESH_API_ROUTE, { headers: { Authorization: `Bearer ${token}` } })
.json<RefreshTokenResponse>();
}

View File

@@ -0,0 +1,20 @@
import ky from "ky";
import { BASE_URL } from "../model/const";
import { useTokenStore } from "../model";
export const api = ky.create({
prefixUrl: BASE_URL,
hooks: {
beforeRequest: [
(request) => {
const token = useTokenStore.getState().accessToken;
if (token) {
request.headers.set("Authorization", `Bearer ${token}`);
}
return request;
},
],
},
});

2
src/shared/api/index.ts Normal file
View File

@@ -0,0 +1,2 @@
export * from "./model";
export { api } from "./config/api";

View File

@@ -2,3 +2,5 @@ export const BASE_URL =
import.meta.env.VITE_API_BASE_URL || "https://localhost:3001"; import.meta.env.VITE_API_BASE_URL || "https://localhost:3001";
export const UNEXPECTED_ERROR_MESSAGE = "An unexpected error occured"; export const UNEXPECTED_ERROR_MESSAGE = "An unexpected error occured";
export const MOCK_TOKEN = "mock.access.token";
export const MOCK_FRESH_TOKEN = "mock.fresh.access.token";

View File

@@ -0,0 +1,3 @@
export * from "./types";
export * from "./stores/tokenStore";
export * from "./const";

View File

@@ -0,0 +1,45 @@
import { setupServer } from "msw/node";
import { MOCK_TOKEN } from "../const";
import { defaultStoreState, useTokenStore } from "./tokenStore";
import { refreshMock } from "shared/api/calls";
const server = setupServer(refreshMock);
describe("tokenStore", () => {
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => {
useTokenStore.getState().reset();
server.resetHandlers();
});
afterAll(() => server.close());
describe("reset", () => {
it("should reset the store to default state", () => {
useTokenStore.getState().reset();
expect(useTokenStore.getState()).toMatchObject(defaultStoreState);
});
});
describe("refreshToken", () => {
it("should update access token after successful refresh", async () => {
useTokenStore.setState({ accessToken: MOCK_TOKEN });
await useTokenStore.getState().refreshToken();
const { accessToken, error } = useTokenStore.getState();
expect(accessToken).toBeDefined();
expect(error).toBeNull();
});
it("should set error if refresh fails", async () => {
useTokenStore.setState({ accessToken: "old_token" });
await useTokenStore.getState().refreshToken();
const { error } = useTokenStore.getState();
expect(error).toBeDefined();
});
});
});

View File

@@ -0,0 +1,39 @@
import { create } from "zustand";
import type { TokenStore, TokenStoreState } from "../types";
import { callApi } from "shared/utils";
import { refresh } from "../../calls/refresh";
import { UNEXPECTED_ERROR_MESSAGE } from "../const";
export const defaultStoreState: TokenStoreState = {
accessToken: null,
error: null,
};
export const useTokenStore = create<TokenStore>()((set, get) => ({
...defaultStoreState,
reset: () => set(defaultStoreState),
refreshToken: async () => {
try {
const currentToken = get().accessToken;
if (!currentToken) {
return;
}
const [refreshResponse, refreshError] = await callApi(() =>
refresh(currentToken),
);
if (refreshError) {
set({ error: refreshError });
return;
}
set({ accessToken: refreshResponse?.accessToken });
} catch (error) {
console.error(error);
set({
error: new Error(UNEXPECTED_ERROR_MESSAGE),
});
}
},
}));

View File

@@ -0,0 +1,17 @@
import type { ApiError } from "shared/utils";
export interface TokenStoreState {
accessToken: string | null;
error: ApiError | Error | null;
}
export interface TokenStoreActions {
reset: () => void;
refreshToken: () => Promise<void>;
}
export type TokenStore = TokenStoreState & TokenStoreActions;
export interface RefreshTokenResponse {
accessToken: string;
}

View File

@@ -1,6 +0,0 @@
import ky from "ky";
import { BASE_URL } from "./constants";
export const api = ky.create({
prefixUrl: BASE_URL,
});

View File

@@ -1,2 +0,0 @@
export * from "./api/constants";
export * from "./api/httpClient";

View File

@@ -1,32 +1,59 @@
import { defineConfig } from "vitest/config"; import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import path from "path"; import path from "path";
import { fileURLToPath } from 'node:url';
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin';
import { playwright } from '@vitest/browser-playwright';
const dirname = typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url));
// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
export default defineConfig({ export default defineConfig({
plugins: [ plugins: [react({
react({
babel: { babel: {
plugins: [["babel-plugin-react-compiler", {}]], plugins: [["babel-plugin-react-compiler", {}]]
}, }
}), })],
],
resolve: { resolve: {
alias: { alias: {
shared: path.resolve(__dirname, "src/shared"), shared: path.resolve(__dirname, "src/shared"),
entities: path.resolve(__dirname, "src/entities"), entities: path.resolve(__dirname, "src/entities"),
features: path.resolve(__dirname, "src/features"), features: path.resolve(__dirname, "src/features"),
widgets: path.resolve(__dirname, "src/widgets"), widgets: path.resolve(__dirname, "src/widgets"),
app: path.resolve(__dirname, "src/app"), app: path.resolve(__dirname, "src/app")
}, }
}, },
test: { test: {
globals: true,
environment: "jsdom",
setupFiles: ["./src/shared/config/test/setup.ts"],
coverage: { coverage: {
provider: "v8", provider: "v8",
reporter: ["text", "json", "html"], reporter: ["text", "json", "html"],
exclude: ["node_modules/", "src/test/"], exclude: ["node_modules/", "src/test/"]
},
}, },
projects: [{
extends: true,
test: {
globals: true,
environment: "jsdom",
setupFiles: ["./src/shared/config/test/setup.ts"]
}
}, {
extends: true,
plugins: [
// The plugin will run tests for the stories defined in your Storybook config
// See options at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon#storybooktest
storybookTest({
configDir: path.join(dirname, '.storybook')
})],
test: {
name: 'storybook',
browser: {
enabled: true,
headless: true,
provider: playwright({}),
instances: [{
browser: 'chromium'
}]
}
}
}]
}
}); });

1
vitest.shims.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="@vitest/browser-playwright" />

946
yarn.lock

File diff suppressed because it is too large Load Diff