tests passing
This commit is contained in:
parent
0995e1cc77
commit
7ebfb7a2dd
20 changed files with 2009 additions and 126 deletions
112
frontend/app/auth-context.tsx
Normal file
112
frontend/app/auth-context.tsx
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
"use client";
|
||||
|
||||
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
token: string | null;
|
||||
isLoading: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
register: (email: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const storedToken = localStorage.getItem("token");
|
||||
if (storedToken) {
|
||||
setToken(storedToken);
|
||||
fetchUser(storedToken);
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchUser = async (authToken: string) => {
|
||||
try {
|
||||
const res = await fetch("http://localhost:8000/api/auth/me", {
|
||||
headers: { Authorization: `Bearer ${authToken}` },
|
||||
});
|
||||
if (res.ok) {
|
||||
const userData = await res.json();
|
||||
setUser(userData);
|
||||
} else {
|
||||
localStorage.removeItem("token");
|
||||
setToken(null);
|
||||
}
|
||||
} catch {
|
||||
localStorage.removeItem("token");
|
||||
setToken(null);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const res = await fetch("http://localhost:8000/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.detail || "Login failed");
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
localStorage.setItem("token", data.access_token);
|
||||
setToken(data.access_token);
|
||||
setUser(data.user);
|
||||
};
|
||||
|
||||
const register = async (email: string, password: string) => {
|
||||
const res = await fetch("http://localhost:8000/api/auth/register", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.detail || "Registration failed");
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
localStorage.setItem("token", data.access_token);
|
||||
setToken(data.access_token);
|
||||
setUser(data.user);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem("token");
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, token, isLoading, login, register, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error("useAuth must be used within an AuthProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
|
|
@ -1,8 +1,44 @@
|
|||
import { AuthProvider } from "./auth-context";
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>{children}</body>
|
||||
<head>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Instrument+Serif:ital@0;1&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<style>{`
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
font-family: 'DM Sans', system-ui, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
input:focus {
|
||||
border-color: rgba(139, 92, 246, 0.5) !important;
|
||||
box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1) !important;
|
||||
}
|
||||
button:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 6px 20px rgba(99, 102, 241, 0.5);
|
||||
}
|
||||
button:active:not(:disabled) {
|
||||
transform: translateY(0);
|
||||
}
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
`}</style>
|
||||
</head>
|
||||
<body>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
36
frontend/app/login/page.test.tsx
Normal file
36
frontend/app/login/page.test.tsx
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { render, screen, cleanup } from "@testing-library/react";
|
||||
import { expect, test, vi, beforeEach, afterEach } from "vitest";
|
||||
import LoginPage from "./page";
|
||||
|
||||
const mockPush = vi.fn();
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: mockPush }),
|
||||
}));
|
||||
|
||||
vi.mock("../auth-context", () => ({
|
||||
useAuth: () => ({ login: vi.fn() }),
|
||||
}));
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
afterEach(() => cleanup());
|
||||
|
||||
test("renders login form with title", () => {
|
||||
render(<LoginPage />);
|
||||
expect(screen.getByText("Welcome back")).toBeDefined();
|
||||
});
|
||||
|
||||
test("renders email and password inputs", () => {
|
||||
render(<LoginPage />);
|
||||
expect(screen.getByLabelText("Email")).toBeDefined();
|
||||
expect(screen.getByLabelText("Password")).toBeDefined();
|
||||
});
|
||||
|
||||
test("renders sign in button", () => {
|
||||
render(<LoginPage />);
|
||||
expect(screen.getByRole("button", { name: "Sign in" })).toBeDefined();
|
||||
});
|
||||
|
||||
test("renders link to signup", () => {
|
||||
render(<LoginPage />);
|
||||
expect(screen.getByText("Sign up")).toBeDefined();
|
||||
});
|
||||
195
frontend/app/login/page.tsx
Normal file
195
frontend/app/login/page.tsx
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth } from "../auth-context";
|
||||
|
||||
export default function LoginPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const { login } = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
await login(email, password);
|
||||
router.push("/");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Login failed");
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main style={styles.main}>
|
||||
<div style={styles.container}>
|
||||
<div style={styles.card}>
|
||||
<div style={styles.header}>
|
||||
<h1 style={styles.title}>Welcome back</h1>
|
||||
<p style={styles.subtitle}>Sign in to your account</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} style={styles.form}>
|
||||
{error && <div style={styles.error}>{error}</div>}
|
||||
|
||||
<div style={styles.field}>
|
||||
<label htmlFor="email" style={styles.label}>Email</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
style={styles.input}
|
||||
placeholder="you@example.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={styles.field}>
|
||||
<label htmlFor="password" style={styles.label}>Password</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
style={styles.input}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
style={{
|
||||
...styles.button,
|
||||
opacity: isSubmitting ? 0.7 : 1,
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? "Signing in..." : "Sign in"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p style={styles.footer}>
|
||||
Don't have an account?{" "}
|
||||
<a href="/signup" style={styles.link}>
|
||||
Sign up
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const styles: Record<string, React.CSSProperties> = {
|
||||
main: {
|
||||
minHeight: "100vh",
|
||||
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
padding: "1rem",
|
||||
},
|
||||
container: {
|
||||
width: "100%",
|
||||
maxWidth: "420px",
|
||||
},
|
||||
card: {
|
||||
background: "rgba(255, 255, 255, 0.03)",
|
||||
backdropFilter: "blur(10px)",
|
||||
border: "1px solid rgba(255, 255, 255, 0.08)",
|
||||
borderRadius: "24px",
|
||||
padding: "3rem 2.5rem",
|
||||
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.5)",
|
||||
},
|
||||
header: {
|
||||
textAlign: "center" as const,
|
||||
marginBottom: "2.5rem",
|
||||
},
|
||||
title: {
|
||||
fontFamily: "'Instrument Serif', Georgia, serif",
|
||||
fontSize: "2.5rem",
|
||||
fontWeight: 400,
|
||||
color: "#fff",
|
||||
margin: 0,
|
||||
letterSpacing: "-0.02em",
|
||||
},
|
||||
subtitle: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
color: "rgba(255, 255, 255, 0.5)",
|
||||
marginTop: "0.5rem",
|
||||
fontSize: "0.95rem",
|
||||
},
|
||||
form: {
|
||||
display: "flex",
|
||||
flexDirection: "column" as const,
|
||||
gap: "1.5rem",
|
||||
},
|
||||
field: {
|
||||
display: "flex",
|
||||
flexDirection: "column" as const,
|
||||
gap: "0.5rem",
|
||||
},
|
||||
label: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
color: "rgba(255, 255, 255, 0.7)",
|
||||
fontSize: "0.875rem",
|
||||
fontWeight: 500,
|
||||
},
|
||||
input: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
padding: "0.875rem 1rem",
|
||||
fontSize: "1rem",
|
||||
background: "rgba(255, 255, 255, 0.05)",
|
||||
border: "1px solid rgba(255, 255, 255, 0.1)",
|
||||
borderRadius: "12px",
|
||||
color: "#fff",
|
||||
outline: "none",
|
||||
transition: "border-color 0.2s, box-shadow 0.2s",
|
||||
},
|
||||
button: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
marginTop: "0.5rem",
|
||||
padding: "1rem",
|
||||
fontSize: "1rem",
|
||||
fontWeight: 600,
|
||||
background: "linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",
|
||||
color: "#fff",
|
||||
border: "none",
|
||||
borderRadius: "12px",
|
||||
cursor: "pointer",
|
||||
transition: "transform 0.2s, box-shadow 0.2s",
|
||||
boxShadow: "0 4px 14px rgba(99, 102, 241, 0.4)",
|
||||
},
|
||||
error: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
padding: "0.875rem 1rem",
|
||||
background: "rgba(239, 68, 68, 0.1)",
|
||||
border: "1px solid rgba(239, 68, 68, 0.3)",
|
||||
borderRadius: "12px",
|
||||
color: "#fca5a5",
|
||||
fontSize: "0.875rem",
|
||||
textAlign: "center" as const,
|
||||
},
|
||||
footer: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
textAlign: "center" as const,
|
||||
marginTop: "2rem",
|
||||
color: "rgba(255, 255, 255, 0.5)",
|
||||
fontSize: "0.875rem",
|
||||
},
|
||||
link: {
|
||||
color: "#a78bfa",
|
||||
textDecoration: "none",
|
||||
fontWeight: 500,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -1,68 +1,199 @@
|
|||
import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
|
||||
import { expect, test, vi, beforeEach, afterEach } from "vitest";
|
||||
import { expect, test, vi, beforeEach, afterEach, describe } from "vitest";
|
||||
import Home from "./page";
|
||||
|
||||
// Mock next/navigation
|
||||
const mockPush = vi.fn();
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
push: mockPush,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Default mock values
|
||||
let mockUser: { id: number; email: string } | null = { id: 1, email: "test@example.com" };
|
||||
let mockToken: string | null = "valid-token";
|
||||
let mockIsLoading = false;
|
||||
const mockLogout = vi.fn();
|
||||
|
||||
vi.mock("./auth-context", () => ({
|
||||
useAuth: () => ({
|
||||
user: mockUser,
|
||||
token: mockToken,
|
||||
isLoading: mockIsLoading,
|
||||
logout: mockLogout,
|
||||
}),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllMocks();
|
||||
// Reset to authenticated state
|
||||
mockUser = { id: 1, email: "test@example.com" };
|
||||
mockToken = "valid-token";
|
||||
mockIsLoading = false;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
test("renders loading state initially", () => {
|
||||
vi.spyOn(global, "fetch").mockImplementation(() => new Promise(() => {}));
|
||||
render(<Home />);
|
||||
expect(screen.getByText("...")).toBeDefined();
|
||||
});
|
||||
describe("Home - Authenticated", () => {
|
||||
test("renders loading state when isLoading is true", () => {
|
||||
mockIsLoading = true;
|
||||
vi.spyOn(global, "fetch").mockImplementation(() => new Promise(() => {}));
|
||||
|
||||
test("renders counter value after fetch", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
json: () => Promise.resolve({ value: 42 }),
|
||||
} as Response);
|
||||
render(<Home />);
|
||||
expect(screen.getByText("Loading...")).toBeDefined();
|
||||
});
|
||||
|
||||
render(<Home />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("42")).toBeDefined();
|
||||
test("renders user email in header", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
json: () => Promise.resolve({ value: 42 }),
|
||||
} as Response);
|
||||
|
||||
render(<Home />);
|
||||
expect(screen.getByText("test@example.com")).toBeDefined();
|
||||
});
|
||||
|
||||
test("renders sign out button", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
json: () => Promise.resolve({ value: 42 }),
|
||||
} as Response);
|
||||
|
||||
render(<Home />);
|
||||
expect(screen.getByText("Sign out")).toBeDefined();
|
||||
});
|
||||
|
||||
test("clicking sign out calls logout", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
json: () => Promise.resolve({ value: 42 }),
|
||||
} as Response);
|
||||
|
||||
render(<Home />);
|
||||
fireEvent.click(screen.getByText("Sign out"));
|
||||
expect(mockLogout).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("renders counter value after fetch", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
json: () => Promise.resolve({ value: 42 }),
|
||||
} as Response);
|
||||
|
||||
render(<Home />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("42")).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
test("fetches counter with auth header", async () => {
|
||||
const fetchSpy = vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
json: () => Promise.resolve({ value: 0 }),
|
||||
} as Response);
|
||||
|
||||
render(<Home />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
"http://localhost:8000/api/counter",
|
||||
expect.objectContaining({
|
||||
headers: { Authorization: "Bearer valid-token" },
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("renders increment button", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
json: () => Promise.resolve({ value: 0 }),
|
||||
} as Response);
|
||||
|
||||
render(<Home />);
|
||||
expect(screen.getByText("Increment")).toBeDefined();
|
||||
});
|
||||
|
||||
test("clicking increment button calls API with auth header", async () => {
|
||||
const fetchSpy = vi
|
||||
.spyOn(global, "fetch")
|
||||
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 0 }) } as Response)
|
||||
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 1 }) } as Response);
|
||||
|
||||
render(<Home />);
|
||||
await waitFor(() => expect(screen.getByText("0")).toBeDefined());
|
||||
|
||||
fireEvent.click(screen.getByText("Increment"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
"http://localhost:8000/api/counter/increment",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer valid-token" },
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("clicking increment updates displayed count", async () => {
|
||||
vi.spyOn(global, "fetch")
|
||||
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 0 }) } as Response)
|
||||
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 1 }) } as Response);
|
||||
|
||||
render(<Home />);
|
||||
await waitFor(() => expect(screen.getByText("0")).toBeDefined());
|
||||
|
||||
fireEvent.click(screen.getByText("Increment"));
|
||||
await waitFor(() => expect(screen.getByText("1")).toBeDefined());
|
||||
});
|
||||
});
|
||||
|
||||
test("renders +1 button", async () => {
|
||||
vi.spyOn(global, "fetch").mockResolvedValue({
|
||||
json: () => Promise.resolve({ value: 0 }),
|
||||
} as Response);
|
||||
describe("Home - Unauthenticated", () => {
|
||||
test("redirects to login when not authenticated", async () => {
|
||||
mockUser = null;
|
||||
mockToken = null;
|
||||
|
||||
render(<Home />);
|
||||
expect(screen.getByText("+1")).toBeDefined();
|
||||
});
|
||||
render(<Home />);
|
||||
|
||||
test("clicking button calls increment endpoint", async () => {
|
||||
const fetchSpy = vi.spyOn(global, "fetch")
|
||||
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 0 }) } as Response)
|
||||
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 1 }) } as Response);
|
||||
await waitFor(() => {
|
||||
expect(mockPush).toHaveBeenCalledWith("/login");
|
||||
});
|
||||
});
|
||||
|
||||
render(<Home />);
|
||||
await waitFor(() => expect(screen.getByText("0")).toBeDefined());
|
||||
test("returns null when not authenticated", () => {
|
||||
mockUser = null;
|
||||
mockToken = null;
|
||||
|
||||
fireEvent.click(screen.getByText("+1"));
|
||||
const { container } = render(<Home />);
|
||||
// Should render nothing (just redirects)
|
||||
expect(container.querySelector("main")).toBeNull();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
"http://localhost:8000/api/counter/increment",
|
||||
{ method: "POST" }
|
||||
);
|
||||
test("does not fetch counter when no token", () => {
|
||||
mockUser = null;
|
||||
mockToken = null;
|
||||
const fetchSpy = vi.spyOn(global, "fetch");
|
||||
|
||||
render(<Home />);
|
||||
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test("clicking button updates displayed count", async () => {
|
||||
vi.spyOn(global, "fetch")
|
||||
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 0 }) } as Response)
|
||||
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 1 }) } as Response);
|
||||
describe("Home - Loading State", () => {
|
||||
test("does not redirect while loading", () => {
|
||||
mockIsLoading = true;
|
||||
mockUser = null;
|
||||
mockToken = null;
|
||||
|
||||
render(<Home />);
|
||||
await waitFor(() => expect(screen.getByText("0")).toBeDefined());
|
||||
render(<Home />);
|
||||
|
||||
fireEvent.click(screen.getByText("+1"));
|
||||
await waitFor(() => expect(screen.getByText("1")).toBeDefined());
|
||||
expect(mockPush).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("shows loading indicator while loading", () => {
|
||||
mockIsLoading = true;
|
||||
|
||||
render(<Home />);
|
||||
|
||||
expect(screen.getByText("Loading...")).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,40 +1,177 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth } from "./auth-context";
|
||||
|
||||
export default function Home() {
|
||||
const [count, setCount] = useState<number | null>(null);
|
||||
const { user, token, isLoading, logout } = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
fetch("http://localhost:8000/api/counter")
|
||||
.then((res) => res.json())
|
||||
.then((data) => setCount(data.value));
|
||||
}, []);
|
||||
if (!isLoading && !user) {
|
||||
router.push("/login");
|
||||
}
|
||||
}, [isLoading, user, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
fetch("http://localhost:8000/api/counter", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then((data) => setCount(data.value))
|
||||
.catch(() => setCount(null));
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const increment = async () => {
|
||||
if (!token) return;
|
||||
const res = await fetch("http://localhost:8000/api/counter/increment", {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
const data = await res.json();
|
||||
setCount(data.value);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<main style={styles.main}>
|
||||
<div style={styles.loader}>Loading...</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<main style={{ padding: "2rem", fontFamily: "system-ui", textAlign: "center" }}>
|
||||
<h1 style={{ fontSize: "6rem", margin: "2rem 0" }}>
|
||||
{count === null ? "..." : count}
|
||||
</h1>
|
||||
<button
|
||||
onClick={increment}
|
||||
style={{
|
||||
fontSize: "1.5rem",
|
||||
padding: "1rem 2rem",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
+1
|
||||
</button>
|
||||
<main style={styles.main}>
|
||||
<div style={styles.header}>
|
||||
<div style={styles.userInfo}>
|
||||
<span style={styles.userEmail}>{user.email}</span>
|
||||
<button onClick={logout} style={styles.logoutBtn}>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={styles.content}>
|
||||
<div style={styles.counterCard}>
|
||||
<span style={styles.counterLabel}>Current Count</span>
|
||||
<h1 style={styles.counter}>{count === null ? "..." : count}</h1>
|
||||
<button onClick={increment} style={styles.incrementBtn}>
|
||||
<span style={styles.plusIcon}>+</span>
|
||||
Increment
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const styles: Record<string, React.CSSProperties> = {
|
||||
main: {
|
||||
minHeight: "100vh",
|
||||
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
},
|
||||
loader: {
|
||||
flex: 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
color: "rgba(255, 255, 255, 0.5)",
|
||||
fontSize: "1.125rem",
|
||||
},
|
||||
header: {
|
||||
padding: "1.5rem 2rem",
|
||||
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
|
||||
},
|
||||
userInfo: {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
gap: "1rem",
|
||||
},
|
||||
userEmail: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
color: "rgba(255, 255, 255, 0.6)",
|
||||
fontSize: "0.875rem",
|
||||
},
|
||||
logoutBtn: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
padding: "0.5rem 1rem",
|
||||
fontSize: "0.875rem",
|
||||
fontWeight: 500,
|
||||
background: "rgba(255, 255, 255, 0.05)",
|
||||
color: "rgba(255, 255, 255, 0.7)",
|
||||
border: "1px solid rgba(255, 255, 255, 0.1)",
|
||||
borderRadius: "8px",
|
||||
cursor: "pointer",
|
||||
transition: "all 0.2s",
|
||||
},
|
||||
content: {
|
||||
flex: 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
padding: "2rem",
|
||||
},
|
||||
counterCard: {
|
||||
background: "rgba(255, 255, 255, 0.03)",
|
||||
backdropFilter: "blur(10px)",
|
||||
border: "1px solid rgba(255, 255, 255, 0.08)",
|
||||
borderRadius: "32px",
|
||||
padding: "4rem 5rem",
|
||||
textAlign: "center",
|
||||
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.5)",
|
||||
},
|
||||
counterLabel: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
display: "block",
|
||||
color: "rgba(255, 255, 255, 0.4)",
|
||||
fontSize: "0.875rem",
|
||||
textTransform: "uppercase",
|
||||
letterSpacing: "0.1em",
|
||||
marginBottom: "1rem",
|
||||
},
|
||||
counter: {
|
||||
fontFamily: "'Instrument Serif', Georgia, serif",
|
||||
fontSize: "8rem",
|
||||
fontWeight: 400,
|
||||
color: "#fff",
|
||||
margin: 0,
|
||||
lineHeight: 1,
|
||||
background: "linear-gradient(135deg, #fff 0%, #a78bfa 100%)",
|
||||
WebkitBackgroundClip: "text",
|
||||
WebkitTextFillColor: "transparent",
|
||||
backgroundClip: "text",
|
||||
},
|
||||
incrementBtn: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
marginTop: "2.5rem",
|
||||
padding: "1rem 2.5rem",
|
||||
fontSize: "1.125rem",
|
||||
fontWeight: 600,
|
||||
background: "linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",
|
||||
color: "#fff",
|
||||
border: "none",
|
||||
borderRadius: "16px",
|
||||
cursor: "pointer",
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: "0.5rem",
|
||||
transition: "transform 0.2s, box-shadow 0.2s",
|
||||
boxShadow: "0 4px 14px rgba(99, 102, 241, 0.4)",
|
||||
},
|
||||
plusIcon: {
|
||||
fontSize: "1.5rem",
|
||||
fontWeight: 400,
|
||||
},
|
||||
};
|
||||
|
|
|
|||
37
frontend/app/signup/page.test.tsx
Normal file
37
frontend/app/signup/page.test.tsx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { render, screen, cleanup } from "@testing-library/react";
|
||||
import { expect, test, vi, beforeEach, afterEach } from "vitest";
|
||||
import SignupPage from "./page";
|
||||
|
||||
const mockPush = vi.fn();
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: mockPush }),
|
||||
}));
|
||||
|
||||
vi.mock("../auth-context", () => ({
|
||||
useAuth: () => ({ register: vi.fn() }),
|
||||
}));
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
afterEach(() => cleanup());
|
||||
|
||||
test("renders signup form with title", () => {
|
||||
render(<SignupPage />);
|
||||
expect(screen.getByRole("heading", { name: "Create account" })).toBeDefined();
|
||||
});
|
||||
|
||||
test("renders email and password inputs", () => {
|
||||
render(<SignupPage />);
|
||||
expect(screen.getByLabelText("Email")).toBeDefined();
|
||||
expect(screen.getByLabelText("Password")).toBeDefined();
|
||||
expect(screen.getByLabelText("Confirm Password")).toBeDefined();
|
||||
});
|
||||
|
||||
test("renders create account button", () => {
|
||||
render(<SignupPage />);
|
||||
expect(screen.getByRole("button", { name: "Create account" })).toBeDefined();
|
||||
});
|
||||
|
||||
test("renders link to login", () => {
|
||||
render(<SignupPage />);
|
||||
expect(screen.getByText("Sign in")).toBeDefined();
|
||||
});
|
||||
220
frontend/app/signup/page.tsx
Normal file
220
frontend/app/signup/page.tsx
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth } from "../auth-context";
|
||||
|
||||
export default function SignupPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const { register } = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
setError("Passwords do not match");
|
||||
return;
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
setError("Password must be at least 6 characters");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
await register(email, password);
|
||||
router.push("/");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Registration failed");
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main style={styles.main}>
|
||||
<div style={styles.container}>
|
||||
<div style={styles.card}>
|
||||
<div style={styles.header}>
|
||||
<h1 style={styles.title}>Create account</h1>
|
||||
<p style={styles.subtitle}>Get started with your journey</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} style={styles.form}>
|
||||
{error && <div style={styles.error}>{error}</div>}
|
||||
|
||||
<div style={styles.field}>
|
||||
<label htmlFor="email" style={styles.label}>Email</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
style={styles.input}
|
||||
placeholder="you@example.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={styles.field}>
|
||||
<label htmlFor="password" style={styles.label}>Password</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
style={styles.input}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={styles.field}>
|
||||
<label htmlFor="confirmPassword" style={styles.label}>Confirm Password</label>
|
||||
<input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
style={styles.input}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
style={{
|
||||
...styles.button,
|
||||
opacity: isSubmitting ? 0.7 : 1,
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? "Creating account..." : "Create account"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p style={styles.footer}>
|
||||
Already have an account?{" "}
|
||||
<a href="/login" style={styles.link}>
|
||||
Sign in
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const styles: Record<string, React.CSSProperties> = {
|
||||
main: {
|
||||
minHeight: "100vh",
|
||||
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
padding: "1rem",
|
||||
},
|
||||
container: {
|
||||
width: "100%",
|
||||
maxWidth: "420px",
|
||||
},
|
||||
card: {
|
||||
background: "rgba(255, 255, 255, 0.03)",
|
||||
backdropFilter: "blur(10px)",
|
||||
border: "1px solid rgba(255, 255, 255, 0.08)",
|
||||
borderRadius: "24px",
|
||||
padding: "3rem 2.5rem",
|
||||
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.5)",
|
||||
},
|
||||
header: {
|
||||
textAlign: "center" as const,
|
||||
marginBottom: "2.5rem",
|
||||
},
|
||||
title: {
|
||||
fontFamily: "'Instrument Serif', Georgia, serif",
|
||||
fontSize: "2.5rem",
|
||||
fontWeight: 400,
|
||||
color: "#fff",
|
||||
margin: 0,
|
||||
letterSpacing: "-0.02em",
|
||||
},
|
||||
subtitle: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
color: "rgba(255, 255, 255, 0.5)",
|
||||
marginTop: "0.5rem",
|
||||
fontSize: "0.95rem",
|
||||
},
|
||||
form: {
|
||||
display: "flex",
|
||||
flexDirection: "column" as const,
|
||||
gap: "1.5rem",
|
||||
},
|
||||
field: {
|
||||
display: "flex",
|
||||
flexDirection: "column" as const,
|
||||
gap: "0.5rem",
|
||||
},
|
||||
label: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
color: "rgba(255, 255, 255, 0.7)",
|
||||
fontSize: "0.875rem",
|
||||
fontWeight: 500,
|
||||
},
|
||||
input: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
padding: "0.875rem 1rem",
|
||||
fontSize: "1rem",
|
||||
background: "rgba(255, 255, 255, 0.05)",
|
||||
border: "1px solid rgba(255, 255, 255, 0.1)",
|
||||
borderRadius: "12px",
|
||||
color: "#fff",
|
||||
outline: "none",
|
||||
transition: "border-color 0.2s, box-shadow 0.2s",
|
||||
},
|
||||
button: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
marginTop: "0.5rem",
|
||||
padding: "1rem",
|
||||
fontSize: "1rem",
|
||||
fontWeight: 600,
|
||||
background: "linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",
|
||||
color: "#fff",
|
||||
border: "none",
|
||||
borderRadius: "12px",
|
||||
cursor: "pointer",
|
||||
transition: "transform 0.2s, box-shadow 0.2s",
|
||||
boxShadow: "0 4px 14px rgba(99, 102, 241, 0.4)",
|
||||
},
|
||||
error: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
padding: "0.875rem 1rem",
|
||||
background: "rgba(239, 68, 68, 0.1)",
|
||||
border: "1px solid rgba(239, 68, 68, 0.3)",
|
||||
borderRadius: "12px",
|
||||
color: "#fca5a5",
|
||||
fontSize: "0.875rem",
|
||||
textAlign: "center" as const,
|
||||
},
|
||||
footer: {
|
||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||
textAlign: "center" as const,
|
||||
marginTop: "2rem",
|
||||
color: "rgba(255, 255, 255, 0.5)",
|
||||
fontSize: "0.875rem",
|
||||
},
|
||||
link: {
|
||||
color: "#a78bfa",
|
||||
textDecoration: "none",
|
||||
fontWeight: 500,
|
||||
},
|
||||
};
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue