Compare commits
28 Commits
db42c87489
...
feature/fr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f71ed9285b | ||
|
|
6516172a6b | ||
|
|
f98ccf468c | ||
|
|
4d95159c4f | ||
|
|
e7ac79049d | ||
|
|
85763e568f | ||
|
|
98e3133d88 | ||
|
|
8d283064a0 | ||
|
|
a6f4b993dd | ||
|
|
3d7eb850ec | ||
|
|
69d026afce | ||
|
|
87511398fb | ||
|
|
542de6c540 | ||
|
|
6d81eaba4b | ||
|
|
5b49398665 | ||
| 6751c7fc04 | |||
|
|
83fbf83bae | ||
|
|
576665f32b | ||
|
|
4d854d08a3 | ||
|
|
70bcf7fdcf | ||
|
|
c006a94c4d | ||
|
|
e4630a7fcb | ||
|
|
c41f02f505 | ||
|
|
683443673e | ||
|
|
1f20f11852 | ||
|
|
c378f7c83a | ||
|
|
8cea93220b | ||
|
|
b871bf27de |
@@ -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 globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
@@ -5,9 +8,7 @@ import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
export default defineConfig([globalIgnores(['dist']), {
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
@@ -19,5 +20,4 @@ export default defineConfig([
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
}, ...storybook.configs["flat/recommended"]])
|
||||
|
||||
13
package.json
13
package.json
@@ -10,7 +10,9 @@
|
||||
"preview": "vite preview",
|
||||
"test:unit": "vitest",
|
||||
"test:run": "vitest run",
|
||||
"test:coverage": "vitest run --coverage"
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"storybook": "storybook dev -p 6006",
|
||||
"build-storybook": "storybook build"
|
||||
},
|
||||
"dependencies": {
|
||||
"ky": "^1.14.3",
|
||||
@@ -19,8 +21,13 @@
|
||||
"zustand": "^5.0.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@chromatic-com/storybook": "^5.0.2",
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@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/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
@@ -29,14 +36,18 @@
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/browser-playwright": "4.1.0",
|
||||
"@vitest/coverage-v8": "^4.1.0",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.24",
|
||||
"eslint-plugin-storybook": "^10.3.3",
|
||||
"globals": "^16.5.0",
|
||||
"jsdom": "^29.0.0",
|
||||
"msw": "^2.12.11",
|
||||
"playwright": "^1.58.2",
|
||||
"storybook": "^10.3.3",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.48.0",
|
||||
"vite": "^7.3.1",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export * from "./login";
|
||||
export * from "./register";
|
||||
export * from "./logout";
|
||||
export * from "../../../../shared/api/calls/refresh";
|
||||
export * from "./mocks";
|
||||
|
||||
@@ -4,7 +4,7 @@ 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_PASSWORD = "100%GoodPassword";
|
||||
|
||||
export const MOCK_EXISTING_USER: User = {
|
||||
id: "1",
|
||||
|
||||
@@ -2,17 +2,7 @@ import { api as baseApi, useTokenStore } from "shared/api";
|
||||
|
||||
export const authHttpClient = baseApi.extend({
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
(request) => {
|
||||
const token = useTokenStore.getState().accessToken;
|
||||
|
||||
if (token) {
|
||||
request.headers.set("Authorization", `Bearer ${token}`);
|
||||
}
|
||||
|
||||
return request;
|
||||
},
|
||||
],
|
||||
beforeRequest: [],
|
||||
afterResponse: [
|
||||
async (request, options, response) => {
|
||||
if (response.status !== 401) {
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
export { useAuth } from "./hooks/useAuth/useAuth";
|
||||
export { AuthGuard } from "./hocs/AuthGuard/AuthGuard";
|
||||
|
||||
export * from "./validators";
|
||||
|
||||
2
src/features/auth/lib/validators/index.ts
Normal file
2
src/features/auth/lib/validators/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { validateEmail } from "./validateEmail/validateEmail";
|
||||
export { validatePassword } from "./validatePassword/validatePassword";
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
MAX_DOMAIN_EXTENSION_LENGTH,
|
||||
MAX_DOMAIN_LABEL_LENGTH,
|
||||
MAX_DOMAIN_LENGTH,
|
||||
MAX_LOCAL_PART_LENGTH,
|
||||
validateEmail,
|
||||
} from "./validateEmail";
|
||||
|
||||
describe("validateEmail", () => {
|
||||
describe("Absence of some parts of an email", () => {
|
||||
it("should return false if there's no separator (@ symbol)", () => {
|
||||
expect(validateEmail("testexample.com")).toBe(false);
|
||||
});
|
||||
it("should return false for an email without a domain extension", () => {
|
||||
expect(validateEmail("test@example")).toBe(false);
|
||||
});
|
||||
it("should return false for an email without a domain", () => {
|
||||
expect(validateEmail("test@")).toBe(false);
|
||||
});
|
||||
it("should return false for an email with no local part", () => {
|
||||
expect(validateEmail("@example.com")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Excessive amount of some parts of an email", () => {
|
||||
it("should return false for an email with multiple separators", () => {
|
||||
expect(validateEmail("test@example@com")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Local part", () => {
|
||||
it("should return false for consecutive dots in local part (unquoted)", () => {
|
||||
expect(validateEmail("john..doe@example.com")).toBe(false);
|
||||
});
|
||||
it("should return true for consecutive dots inside a quoted string", () => {
|
||||
expect(validateEmail('"john..doe"@example.com')).toBe(true);
|
||||
});
|
||||
it("should return false for leading/trailing dots in local part", () => {
|
||||
expect(validateEmail(".john@example.com")).toBe(false);
|
||||
expect(validateEmail("john.@example.com")).toBe(false);
|
||||
});
|
||||
it("should return true for special characters in unquoted local part", () => {
|
||||
expect(validateEmail("!#$%&'*+-/=?^_`{|}~@example.com")).toBe(true);
|
||||
});
|
||||
it("should return true for escaped characters and spaces inside quotes", () => {
|
||||
expect(validateEmail('"John Doe"@example.com')).toBe(true);
|
||||
expect(validateEmail('"John\\"Doe"@example.com')).toBe(true);
|
||||
});
|
||||
it("should return false if the local part is too long", () => {
|
||||
const longLocalPart = "a".repeat(MAX_LOCAL_PART_LENGTH + 1);
|
||||
expect(validateEmail(longLocalPart + "@example.com")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Domain", () => {
|
||||
it("should return true for a domain starting with a digit", () => {
|
||||
expect(validateEmail("test@123example.com")).toBe(true);
|
||||
});
|
||||
it("should return false for a domain label ending with a hyphen", () => {
|
||||
expect(validateEmail("test@example-.com")).toBe(false);
|
||||
});
|
||||
it("should return false for a domain label starting with a hyphen", () => {
|
||||
expect(validateEmail("test@-example.com")).toBe(false);
|
||||
});
|
||||
it("should return false if a middle label exceeds maximum allowed characters", () => {
|
||||
const longLabel = "a".repeat(MAX_DOMAIN_LABEL_LENGTH + 1);
|
||||
expect(validateEmail(`test@${longLabel}.com`)).toBe(false);
|
||||
});
|
||||
it("should return true for complex subdomains", () => {
|
||||
expect(validateEmail("test@sub.sub-label.example.com")).toBe(true);
|
||||
});
|
||||
it("should return false if the domain is too long", () => {
|
||||
const longDomain = "a".repeat(MAX_DOMAIN_LENGTH + 1);
|
||||
expect(validateEmail(`test@${longDomain}.com`)).toBe(false);
|
||||
});
|
||||
it("should return false if the domain extension is too long", () => {
|
||||
const longExtension = "a".repeat(MAX_DOMAIN_EXTENSION_LENGTH + 1);
|
||||
expect(validateEmail(`test@example.${longExtension}`)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Valid emails", () => {
|
||||
it("should return true for a valid email", () => {
|
||||
expect(validateEmail("test@example.com")).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
export const MAX_LOCAL_PART_LENGTH = 63;
|
||||
export const MAX_DOMAIN_LENGTH = 255;
|
||||
export const MAX_DOMAIN_EXTENSION_LENGTH = 63;
|
||||
export const MAX_DOMAIN_LABEL_LENGTH = 63;
|
||||
const MAX_DOMAIN_LABEL_LENGTH_WITHOUT_START_AND_END_CHARS = Math.max(
|
||||
MAX_DOMAIN_LABEL_LENGTH - 2,
|
||||
0,
|
||||
);
|
||||
|
||||
// RFC 5322 compliant email regex
|
||||
export const EMAIL_REGEX = new RegExp(
|
||||
"^" +
|
||||
`(?=[^@]{1,${MAX_LOCAL_PART_LENGTH}}@)` +
|
||||
"(?:(?:" +
|
||||
'"(?:[^"\\\\]|\\\\.)+"' + // Quoted string support
|
||||
")|(?:" +
|
||||
"[a-zA-Z0-9!#$%&'*+\\-/=?^_`{|}~]+" +
|
||||
"(?:\\.[a-zA-Z0-9!#$%&'*+\\-/=?^_`{|}~]+)*" + // Dot restrictions
|
||||
"))" +
|
||||
"@" +
|
||||
`(?=.{1,${MAX_DOMAIN_LENGTH}}$)` +
|
||||
`(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,${MAX_DOMAIN_LABEL_LENGTH_WITHOUT_START_AND_END_CHARS}}[a-zA-Z0-9])?\\.)+` +
|
||||
`[a-zA-Z]{2,${MAX_DOMAIN_EXTENSION_LENGTH}}` +
|
||||
"$",
|
||||
);
|
||||
|
||||
/**
|
||||
* Validates an email address using a regular expression.
|
||||
* @param email The email address to validate.
|
||||
* @returns `true` if the email is valid, `false` otherwise.
|
||||
*/
|
||||
export function validateEmail(email: string): boolean {
|
||||
return EMAIL_REGEX.test(email);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
MAX_PASSWORD_LENGTH,
|
||||
MIN_PASSWORD_LENGTH,
|
||||
validatePassword,
|
||||
} from "./validatePassword";
|
||||
|
||||
describe("validatePassword", () => {
|
||||
describe("Absence of necessary characters", () => {
|
||||
it("should return false when the password does not contain a lowercase letter", () => {
|
||||
expect(validatePassword("PASSWORD123!")).toBe(false);
|
||||
});
|
||||
it("should return false when the password does not contain an uppercase letter", () => {
|
||||
expect(validatePassword("password123!")).toBe(false);
|
||||
});
|
||||
it("should return false when the password does not contain a digit", () => {
|
||||
expect(validatePassword("Password!")).toBe(false);
|
||||
});
|
||||
it("should return false when the password does not contain a special character", () => {
|
||||
expect(validatePassword("Password123")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Length requirement", () => {
|
||||
const validChars = "aA1!";
|
||||
|
||||
it("should return false when the password is less than min length", () => {
|
||||
const shortPassword =
|
||||
validChars +
|
||||
"a".repeat(Math.max(0, MIN_PASSWORD_LENGTH - validChars.length - 1));
|
||||
|
||||
expect(validatePassword(shortPassword)).toBe(false);
|
||||
});
|
||||
it("should return true when the password is exactly min length", () => {
|
||||
const exactMinPassword =
|
||||
validChars +
|
||||
"a".repeat(Math.max(0, MIN_PASSWORD_LENGTH - validChars.length));
|
||||
|
||||
expect(validatePassword(exactMinPassword)).toBe(true);
|
||||
});
|
||||
it("should return false when the password is greater than max length", () => {
|
||||
const longPassword =
|
||||
validChars +
|
||||
"a".repeat(Math.max(0, MAX_PASSWORD_LENGTH - validChars.length + 1));
|
||||
|
||||
expect(validatePassword(longPassword)).toBe(false);
|
||||
});
|
||||
it("should return true when the password is exactly max length", () => {
|
||||
const exactMaxPassword =
|
||||
validChars +
|
||||
"a".repeat(Math.max(0, MAX_PASSWORD_LENGTH - validChars.length));
|
||||
|
||||
expect(validatePassword(exactMaxPassword)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Valid password", () => {
|
||||
it("should return true when the password is valid", () => {
|
||||
const validChars = "aA1!";
|
||||
const validPassword =
|
||||
validChars +
|
||||
"a".repeat(Math.max(0, MIN_PASSWORD_LENGTH - validChars.length));
|
||||
|
||||
expect(validatePassword(validPassword)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
export const MIN_PASSWORD_LENGTH = 11;
|
||||
export const MAX_PASSWORD_LENGTH = 63;
|
||||
|
||||
/**
|
||||
* The password regex used to validate passwords.
|
||||
* Uses a case-sensitive regex with at least one lowercase letter, one uppercase letter, one digit, and one special character.
|
||||
*/
|
||||
export const PASSWORD_REGEX = new RegExp(
|
||||
`^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{${MIN_PASSWORD_LENGTH},${MAX_PASSWORD_LENGTH}}$`,
|
||||
);
|
||||
|
||||
/**
|
||||
* Validates a password against the password regex.
|
||||
* @param password The password to validate.
|
||||
* @returns `true` if the password is valid, `false` otherwise.
|
||||
*/
|
||||
export function validatePassword(password: string): boolean {
|
||||
return PASSWORD_REGEX.test(password);
|
||||
}
|
||||
@@ -3,4 +3,7 @@ export * from "./types/service";
|
||||
export * from "./types/store";
|
||||
|
||||
// Stores
|
||||
export * from "./stores/authStore/authStore";
|
||||
export * from "./stores";
|
||||
|
||||
// Selectors
|
||||
export * from "./selectors";
|
||||
|
||||
5
src/features/auth/model/selectors/index.ts
Normal file
5
src/features/auth/model/selectors/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export * from "./selectFormValid/selectFormValid";
|
||||
export * from "./selectAuthData/selectAuthData";
|
||||
export * from "./selectStatusIsLoading/selectStatusIsLoading";
|
||||
export * from "./selectEmail/selectEmail";
|
||||
export * from "./selectPassword/selectPassword";
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { AuthStore } from "../../types/store";
|
||||
|
||||
export const selectEmail = (state: AuthStore) =>
|
||||
state.formData?.email?.value ?? "";
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { AuthStore } from "../../types/store";
|
||||
|
||||
export const selectFormValid = (state: AuthStore) =>
|
||||
Object.values(state.formData).every((field) => field.valid);
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { AuthStore } from "../../types/store";
|
||||
|
||||
export const selectPassword = (state: AuthStore) =>
|
||||
state.formData?.password?.value ?? "";
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { AuthStore } from "../../types/store";
|
||||
|
||||
export const selectStatusIsLoading = (state: AuthStore) =>
|
||||
state.status === "loading";
|
||||
@@ -1,27 +1,50 @@
|
||||
import { setupServer } from "msw/node";
|
||||
import {
|
||||
loginMock,
|
||||
registerMock,
|
||||
logoutMock,
|
||||
refreshMock,
|
||||
} from "../../../api/calls";
|
||||
import * as apiCalls from "../../../api/calls";
|
||||
import { defaultStoreState, useAuthStore } from "./authStore";
|
||||
import {
|
||||
MOCK_EMAIL,
|
||||
MOCK_NEW_EMAIL,
|
||||
MOCK_PASSWORD,
|
||||
} from "../../../api/calls/mocks";
|
||||
import { useTokenStore } from "shared/api";
|
||||
|
||||
const server = setupServer(loginMock, registerMock, logoutMock, refreshMock);
|
||||
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();
|
||||
useTokenStore.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();
|
||||
@@ -30,10 +53,33 @@ describe("authStore", () => {
|
||||
});
|
||||
|
||||
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 () => {
|
||||
await useAuthStore
|
||||
.getState()
|
||||
.login({ email: MOCK_EMAIL, password: MOCK_PASSWORD });
|
||||
useAuthStore.getState().setEmail(MOCK_EMAIL);
|
||||
useAuthStore.getState().setPassword(MOCK_PASSWORD);
|
||||
|
||||
await useAuthStore.getState().login();
|
||||
|
||||
const { user, status, error } = useAuthStore.getState();
|
||||
|
||||
@@ -43,9 +89,10 @@ describe("authStore", () => {
|
||||
});
|
||||
|
||||
it("should set error and update status if login fails", async () => {
|
||||
await useAuthStore
|
||||
.getState()
|
||||
.login({ email: "wrong@test.com", password: "wrongPassword" });
|
||||
useAuthStore.getState().setEmail("wrong@test.com");
|
||||
useAuthStore.getState().setPassword("100%WrongPassword");
|
||||
|
||||
await useAuthStore.getState().login();
|
||||
|
||||
const { status, error } = useAuthStore.getState();
|
||||
|
||||
@@ -55,10 +102,33 @@ describe("authStore", () => {
|
||||
});
|
||||
|
||||
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 () => {
|
||||
await useAuthStore
|
||||
.getState()
|
||||
.register({ email: MOCK_NEW_EMAIL, password: MOCK_PASSWORD });
|
||||
useAuthStore.getState().setEmail(MOCK_NEW_EMAIL);
|
||||
useAuthStore.getState().setPassword(MOCK_PASSWORD);
|
||||
|
||||
await useAuthStore.getState().register();
|
||||
|
||||
const { user, status, error } = useAuthStore.getState();
|
||||
|
||||
@@ -68,9 +138,10 @@ describe("authStore", () => {
|
||||
});
|
||||
|
||||
it("should set error and update status if registration fails", async () => {
|
||||
await useAuthStore
|
||||
.getState()
|
||||
.register({ email: MOCK_EMAIL, password: MOCK_PASSWORD });
|
||||
useAuthStore.getState().setEmail(MOCK_EMAIL);
|
||||
useAuthStore.getState().setPassword(MOCK_PASSWORD);
|
||||
|
||||
await useAuthStore.getState().register();
|
||||
|
||||
const { status, error } = useAuthStore.getState();
|
||||
|
||||
@@ -80,6 +151,14 @@ describe("authStore", () => {
|
||||
});
|
||||
|
||||
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();
|
||||
|
||||
|
||||
@@ -2,20 +2,60 @@ import { create } from "zustand";
|
||||
import type { AuthStore, AuthStoreState } from "../../types/store";
|
||||
import { login, logout, register } from "../../../api";
|
||||
import { callApi } from "shared/utils";
|
||||
import { UNEXPECTED_ERROR_MESSAGE } from "shared/api";
|
||||
import { UNEXPECTED_ERROR_MESSAGE, useTokenStore } from "shared/api";
|
||||
import { selectAuthData, selectFormValid } from "../../selectors";
|
||||
import { validateEmail, validatePassword } from "../../../lib";
|
||||
|
||||
export const defaultStoreState: Readonly<AuthStoreState> = {
|
||||
formData: {
|
||||
email: { value: "", valid: false },
|
||||
password: { value: "", valid: false },
|
||||
},
|
||||
user: undefined,
|
||||
status: "idle",
|
||||
error: null,
|
||||
};
|
||||
|
||||
export const useAuthStore = create<AuthStore>()((set) => ({
|
||||
export const useAuthStore = create<AuthStore>()((set, get) => ({
|
||||
...defaultStoreState,
|
||||
reset: () => set(defaultStoreState),
|
||||
login: async (loginData) => {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
set({ status: "loading" });
|
||||
|
||||
const formValid = selectFormValid(get());
|
||||
|
||||
if (!formValid) {
|
||||
set({ status: "idle" });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const loginData = selectAuthData(get());
|
||||
const [responseData, loginError] = await callApi(() => login(loginData));
|
||||
|
||||
if (loginError) {
|
||||
@@ -28,8 +68,7 @@ export const useAuthStore = create<AuthStore>()((set) => ({
|
||||
user: responseData?.user,
|
||||
error: null,
|
||||
});
|
||||
|
||||
// useTokenStore.setState({ accessToken: responseData?.accessToken });
|
||||
useTokenStore.setState({ accessToken: responseData?.accessToken });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
set({
|
||||
@@ -38,8 +77,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 {
|
||||
const registerData = selectAuthData(get());
|
||||
const [responseData, registerError] = await callApi(() =>
|
||||
register(registerData),
|
||||
);
|
||||
@@ -54,8 +109,7 @@ export const useAuthStore = create<AuthStore>()((set) => ({
|
||||
user: responseData?.user,
|
||||
error: null,
|
||||
});
|
||||
|
||||
// useTokenStore.setState({ accessToken: responseData?.accessToken });
|
||||
useTokenStore.setState({ accessToken: responseData?.accessToken });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
set({
|
||||
@@ -65,12 +119,18 @@ export const useAuthStore = create<AuthStore>()((set) => ({
|
||||
}
|
||||
},
|
||||
logout: async () => {
|
||||
const prevStatus = get().status;
|
||||
|
||||
if (prevStatus === "loading") {
|
||||
return;
|
||||
}
|
||||
|
||||
set({ status: "loading" });
|
||||
try {
|
||||
const [, logoutError] = await callApi(() => logout());
|
||||
|
||||
if (logoutError) {
|
||||
set({ error: logoutError });
|
||||
set({ error: logoutError, status: prevStatus });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -80,7 +140,7 @@ export const useAuthStore = create<AuthStore>()((set) => ({
|
||||
error: null,
|
||||
});
|
||||
|
||||
// useTokenStore.setState({ accessToken: null });
|
||||
useTokenStore.setState({ accessToken: null });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
set({ error: new Error(UNEXPECTED_ERROR_MESSAGE) });
|
||||
|
||||
1
src/features/auth/model/stores/index.ts
Normal file
1
src/features/auth/model/stores/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { useAuthStore } from "./authStore/authStore";
|
||||
@@ -2,9 +2,20 @@ import type { User } from "entities/User";
|
||||
import type { AuthData, AuthStatus } from "./service";
|
||||
import type { ApiError } from "shared/utils";
|
||||
|
||||
export type AuthFormData = {
|
||||
[K in keyof AuthData]: {
|
||||
value: AuthData[K];
|
||||
valid: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export interface AuthStoreState {
|
||||
/**
|
||||
* User's credentials
|
||||
* Form data for login/register forms
|
||||
*/
|
||||
formData: AuthFormData;
|
||||
/**
|
||||
* Current user
|
||||
*/
|
||||
user?: User;
|
||||
/**
|
||||
@@ -17,16 +28,14 @@ export interface AuthStoreState {
|
||||
error: ApiError | Error | null;
|
||||
}
|
||||
|
||||
export type ResetAction = () => void;
|
||||
export type LoginAction = (data: AuthData) => Promise<void>;
|
||||
export type RegisterAction = (data: AuthData) => Promise<void>;
|
||||
export type LogoutAction = () => Promise<void>;
|
||||
|
||||
export interface AuthStoreActions {
|
||||
reset: ResetAction;
|
||||
login: LoginAction;
|
||||
register: RegisterAction;
|
||||
logout: LogoutAction;
|
||||
setEmail: (email: string) => void;
|
||||
setPassword: (password: string) => void;
|
||||
reset: () => void;
|
||||
|
||||
login: () => Promise<void>;
|
||||
register: () => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
}
|
||||
|
||||
export type AuthStore = AuthStoreState & AuthStoreActions;
|
||||
|
||||
14
src/features/auth/ui/DefaultButton/DefaultButton.tsx
Normal file
14
src/features/auth/ui/DefaultButton/DefaultButton.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { ButtonHTMLAttributes } from "react";
|
||||
|
||||
export type ButtonAttributes = ButtonHTMLAttributes<HTMLButtonElement>;
|
||||
|
||||
export function DefaultButtonComponent({
|
||||
disabled,
|
||||
children,
|
||||
}: ButtonAttributes) {
|
||||
return (
|
||||
<button type="submit" disabled={disabled}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
19
src/features/auth/ui/DefaultInput/DefaultInput.tsx
Normal file
19
src/features/auth/ui/DefaultInput/DefaultInput.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { InputHTMLAttributes } from "react";
|
||||
|
||||
export type InputAttributes = InputHTMLAttributes<HTMLInputElement>;
|
||||
|
||||
export function DefaultInputComponent({
|
||||
type,
|
||||
value,
|
||||
onChange,
|
||||
["aria-label"]: ariaLabel,
|
||||
}: InputAttributes) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
aria-label={ariaLabel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
91
src/features/auth/ui/LoginForm/LoginForm.spec.tsx
Normal file
91
src/features/auth/ui/LoginForm/LoginForm.spec.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import { selectAuthData, useAuthStore } from "../../model";
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { LoginForm } from "./LoginForm";
|
||||
import { MOCK_EMAIL, MOCK_PASSWORD } from "../../api";
|
||||
import { useTokenStore } from "shared/api";
|
||||
|
||||
describe("LoginForm", () => {
|
||||
afterEach(() => {
|
||||
useAuthStore.getState().reset();
|
||||
useTokenStore.getState().reset();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should render form", () => {
|
||||
act(() => render(<LoginForm />));
|
||||
const form = screen.getByRole("form");
|
||||
|
||||
expect(form).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("disables submit button when form is invalid", () => {
|
||||
act(() => 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" });
|
||||
|
||||
act(() => 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" });
|
||||
|
||||
act(() => 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 () => {
|
||||
act(() => 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 () => {
|
||||
act(() => 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" });
|
||||
|
||||
act(() => 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();
|
||||
});
|
||||
});
|
||||
12
src/features/auth/ui/LoginForm/LoginForm.stories.ts
Normal file
12
src/features/auth/ui/LoginForm/LoginForm.stories.ts
Normal 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 = {};
|
||||
@@ -1,5 +1,98 @@
|
||||
export function LoginForm() {
|
||||
import {
|
||||
selectEmail,
|
||||
selectFormValid,
|
||||
selectPassword,
|
||||
selectStatusIsLoading,
|
||||
useAuthStore,
|
||||
} from "../../model";
|
||||
import {
|
||||
type SubmitEvent,
|
||||
type ChangeEvent,
|
||||
cloneElement,
|
||||
type ReactElement,
|
||||
} from "react";
|
||||
import {
|
||||
DefaultButtonComponent,
|
||||
type ButtonAttributes,
|
||||
} from "../DefaultButton/DefaultButton";
|
||||
import {
|
||||
DefaultInputComponent,
|
||||
type InputAttributes,
|
||||
} from "../DefaultInput/DefaultInput";
|
||||
|
||||
export interface Props {
|
||||
InputComponent?: ReactElement<InputAttributes>;
|
||||
ButtonComponent?: ReactElement<ButtonAttributes>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Login form component
|
||||
*/
|
||||
export function LoginForm({ InputComponent, ButtonComponent }: Props) {
|
||||
const { setEmail, setPassword, login } = useAuthStore();
|
||||
const email = useAuthStore(selectEmail);
|
||||
const password = useAuthStore(selectPassword);
|
||||
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 (
|
||||
<form>Login Form</form>
|
||||
<form aria-label="Login form" onSubmit={handleSubmit}>
|
||||
{/* EMAIL */}
|
||||
{InputComponent ? (
|
||||
cloneElement(InputComponent, {
|
||||
value: email,
|
||||
onChange: handleEmailChange,
|
||||
"aria-label": "Email",
|
||||
})
|
||||
) : (
|
||||
<DefaultInputComponent
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={handleEmailChange}
|
||||
aria-label="Email"
|
||||
/>
|
||||
)}
|
||||
{/* PASSWORD */}
|
||||
{InputComponent ? (
|
||||
cloneElement(InputComponent, {
|
||||
value: password,
|
||||
onChange: handlePasswordChange,
|
||||
"aria-label": "Password",
|
||||
})
|
||||
) : (
|
||||
<DefaultInputComponent
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={handlePasswordChange}
|
||||
aria-label="Password"
|
||||
/>
|
||||
)}
|
||||
{/* BUTTON */}
|
||||
{ButtonComponent ? (
|
||||
cloneElement(ButtonComponent, {
|
||||
type: "submit",
|
||||
disabled: disabled,
|
||||
})
|
||||
) : (
|
||||
<DefaultButtonComponent disabled={disabled}>
|
||||
Login
|
||||
</DefaultButtonComponent>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
117
src/features/auth/ui/RegisterForm/RegisterForm.spec.tsx
Normal file
117
src/features/auth/ui/RegisterForm/RegisterForm.spec.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
import { act, 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";
|
||||
import { useTokenStore } from "shared/api";
|
||||
|
||||
describe("RegisterForm", () => {
|
||||
afterEach(() => {
|
||||
useAuthStore.getState().reset();
|
||||
useTokenStore.getState().reset();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should render form", () => {
|
||||
act(() => render(<RegisterForm />));
|
||||
|
||||
const form = screen.getByRole("form");
|
||||
expect(form).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should disable button when form is invalid", async () => {
|
||||
act(() => 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" });
|
||||
|
||||
act(() => 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 () => {
|
||||
act(() => 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" });
|
||||
|
||||
act(() => 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 () => {
|
||||
act(() => 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 () => {
|
||||
act(() => 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" });
|
||||
|
||||
act(() => 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();
|
||||
});
|
||||
});
|
||||
12
src/features/auth/ui/RegisterForm/RegisterForm.stories.ts
Normal file
12
src/features/auth/ui/RegisterForm/RegisterForm.stories.ts
Normal 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 = {};
|
||||
@@ -1,5 +1,123 @@
|
||||
export function RegisterForm() {
|
||||
import {
|
||||
cloneElement,
|
||||
useState,
|
||||
type ChangeEvent,
|
||||
type ReactElement,
|
||||
type SubmitEvent,
|
||||
} from "react";
|
||||
import {
|
||||
selectEmail,
|
||||
selectFormValid,
|
||||
selectPassword,
|
||||
selectStatusIsLoading,
|
||||
useAuthStore,
|
||||
} from "../../model";
|
||||
import {
|
||||
DefaultInputComponent,
|
||||
type InputAttributes,
|
||||
} from "../DefaultInput/DefaultInput";
|
||||
import {
|
||||
DefaultButtonComponent,
|
||||
type ButtonAttributes,
|
||||
} from "../DefaultButton/DefaultButton";
|
||||
|
||||
export interface Props {
|
||||
InputComponent?: ReactElement<InputAttributes>;
|
||||
ButtonComponent?: ReactElement<ButtonAttributes>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register form component
|
||||
*/
|
||||
export function RegisterForm({ InputComponent, ButtonComponent }: Props) {
|
||||
const { setEmail, setPassword, register } = useAuthStore();
|
||||
const email = useAuthStore(selectEmail);
|
||||
const password = useAuthStore(selectPassword);
|
||||
|
||||
const [confirmedPassword, setConfirmedPassword] = useState("");
|
||||
|
||||
const formValid = useAuthStore(selectFormValid);
|
||||
const isLoading = useAuthStore(selectStatusIsLoading);
|
||||
|
||||
const passwordMatch = password === 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 (
|
||||
<form>Register Form</form>
|
||||
<form aria-label="Register Form" onSubmit={handleSubmit}>
|
||||
{/* EMAIL */}
|
||||
{InputComponent ? (
|
||||
cloneElement(InputComponent, {
|
||||
value: email,
|
||||
onChange: handleEmailChange,
|
||||
"aria-label": "Email",
|
||||
})
|
||||
) : (
|
||||
<DefaultInputComponent
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={handleEmailChange}
|
||||
aria-label="Email"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* PASSWORD */}
|
||||
{InputComponent ? (
|
||||
cloneElement(InputComponent, {
|
||||
value: password,
|
||||
onChange: handlePasswordChange,
|
||||
"aria-label": "Password",
|
||||
})
|
||||
) : (
|
||||
<DefaultInputComponent
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={handlePasswordChange}
|
||||
aria-label="Password"
|
||||
/>
|
||||
)}
|
||||
{/* PASSWORD */}
|
||||
{InputComponent ? (
|
||||
cloneElement(InputComponent, {
|
||||
value: confirmedPassword,
|
||||
onChange: handleConfirmChange,
|
||||
"aria-label": "Confirm",
|
||||
})
|
||||
) : (
|
||||
<DefaultInputComponent
|
||||
type="password"
|
||||
value={confirmedPassword}
|
||||
onChange={handleConfirmChange}
|
||||
aria-label="Confirm"
|
||||
/>
|
||||
)}
|
||||
{/* BUTTON */}
|
||||
{ButtonComponent ? (
|
||||
cloneElement(ButtonComponent, {
|
||||
type: "submit",
|
||||
disabled: disabled,
|
||||
})
|
||||
) : (
|
||||
<DefaultButtonComponent disabled={disabled}>
|
||||
Register
|
||||
</DefaultButtonComponent>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,32 +1,59 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
import react from "@vitejs/plugin-react";
|
||||
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({
|
||||
plugins: [
|
||||
react({
|
||||
plugins: [react({
|
||||
babel: {
|
||||
plugins: [["babel-plugin-react-compiler", {}]],
|
||||
},
|
||||
}),
|
||||
],
|
||||
plugins: [["babel-plugin-react-compiler", {}]]
|
||||
}
|
||||
})],
|
||||
resolve: {
|
||||
alias: {
|
||||
shared: path.resolve(__dirname, "src/shared"),
|
||||
entities: path.resolve(__dirname, "src/entities"),
|
||||
features: path.resolve(__dirname, "src/features"),
|
||||
widgets: path.resolve(__dirname, "src/widgets"),
|
||||
app: path.resolve(__dirname, "src/app"),
|
||||
},
|
||||
app: path.resolve(__dirname, "src/app")
|
||||
}
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: "jsdom",
|
||||
setupFiles: ["./src/shared/config/test/setup.ts"],
|
||||
coverage: {
|
||||
provider: "v8",
|
||||
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
1
vitest.shims.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="@vitest/browser-playwright" />
|
||||
Reference in New Issue
Block a user