Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19,410 changes: 8,914 additions & 10,496 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

104 changes: 104 additions & 0 deletions src/app/api/user/profile/__tests__/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { NextRequest } from 'next/server';
import { GET, PUT } from '../route';
import { UserRole } from '@/types/api';
import crypto from 'crypto';

vi.mock('@/../infra/edge-config', () => ({
edgeLog: vi.fn(),
}));

function createTestToken(payload: { sub: string; role: string; email?: string }): string {
const secret = process.env.JWT_SECRET || 'test-jwt-secret-key-1234567890!';
const header = { alg: 'HS256', typ: 'JWT' };
const fullPayload = { ...payload, exp: Math.floor(Date.now() / 1000) + 3600 };

const base64UrlEncode = (obj: unknown) =>
Buffer.from(JSON.stringify(obj))
.toString('base64')
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');

const headerB64 = base64UrlEncode(header);
const payloadB64 = base64UrlEncode(fullPayload);
const dataToSign = `${headerB64}.${payloadB64}`;

const signature = crypto
.createHmac('sha256', secret)
.update(dataToSign)
.digest('base64')
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');

return `${dataToSign}.${signature}`;
}

describe('Profile API Route (/api/user/profile)', () => {
beforeEach(() => {
process.env.JWT_SECRET = 'test-jwt-secret-key-1234567890!';
});

it('GET returns default profile when no token is provided', async () => {
const req = new NextRequest('http://localhost:3000/api/user/profile');
const res = await GET(req);
expect(res.status).toBe(200);

const json = await res.json();
expect(json.success).toBe(true);
expect(json.data.name).toBe('John Doe');
});

it('GET returns authenticated user profile when valid token is provided', async () => {
const token = createTestToken({
sub: 'user-789',
role: UserRole.STUDENT,
email: 'alice.smith@example.com',
});

const req = new NextRequest('http://localhost:3000/api/user/profile', {
headers: {
authorization: `Bearer ${token}`,
},
});

const res = await GET(req);
expect(res.status).toBe(200);

const json = await res.json();
expect(json.success).toBe(true);
expect(json.data.name).toBe('Alice Smith');
expect(json.data.email).toBe('alice.smith@example.com');
expect(json.data.initials).toBe('AS');
});

it('PUT updates profile data correctly', async () => {
const token = createTestToken({
sub: 'user-789',
role: UserRole.STUDENT,
email: 'alice.smith@example.com',
});

const updateReq = new NextRequest('http://localhost:3000/api/user/profile', {
method: 'PUT',
headers: {
authorization: `Bearer ${token}`,
'content-type': 'application/json',
},
body: JSON.stringify({
name: 'Alice Johnson',
bio: 'Updated bio for Alice',
}),
});

const res = await PUT(updateReq);
expect(res.status).toBe(200);

const json = await res.json();
expect(json.success).toBe(true);
expect(json.data.name).toBe('Alice Johnson');
expect(json.data.initials).toBe('AJ');
expect(json.data.bio).toBe('Updated bio for Alice');
});
});
50 changes: 43 additions & 7 deletions src/app/profile/__tests__/ProfileTabs.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,25 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';
import { describe, expect, it, beforeEach, vi } from 'vitest';
import { ThemeProvider } from '@/lib/theme-provider';
import ProfileTabs from '../components/ProfileTabs';

beforeEach(() => {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
});

function renderWithTheme(ui: React.ReactElement) {
return render(<ThemeProvider defaultTheme="light">{ui}</ThemeProvider>);
}
Expand All @@ -19,14 +35,32 @@ describe('ProfileTabs', () => {
expect(screen.queryByText('First Course')).not.toBeInTheDocument();
});

it('renders custom authenticated user if passed via initialUser prop', () => {
const authUser = {
initials: 'AS',
name: 'Alice Smith',
email: 'alice@example.com',
bio: 'Instructing Web3',
learningGoal: 'web3-development',
dailyLearningTime: '1-hour',
avatarUrl: '/avatars/alice.png',
};

renderWithTheme(<ProfileTabs initialUser={authUser} />);

expect(screen.getByLabelText('Full Name')).toHaveValue('Alice Smith');
expect(screen.getByLabelText('Email')).toHaveValue('alice@example.com');
});

it('loads settings only when the settings tab is selected', async () => {
const user = userEvent.setup();

renderWithTheme(<ProfileTabs />);
await user.click(screen.getByRole('tab', { name: 'Settings' }));

await waitFor(() =>
expect(screen.getByRole('tabpanel', { name: 'Settings' })).toBeInTheDocument(),
await waitFor(
() => expect(screen.getByRole('tabpanel', { name: 'Settings' })).toBeInTheDocument(),
{ timeout: 3000 },
);
expect(screen.getByRole('tab', { name: 'Settings' })).toHaveAttribute('aria-selected', 'true');
expect(screen.getByRole('switch', { name: 'Notifications' })).toBeChecked();
Expand All @@ -41,8 +75,9 @@ describe('ProfileTabs', () => {
renderWithTheme(<ProfileTabs />);
await user.click(screen.getByRole('tab', { name: 'Achievements' }));

await waitFor(() =>
expect(screen.getByRole('tabpanel', { name: 'Achievements' })).toBeInTheDocument(),
await waitFor(
() => expect(screen.getByRole('tabpanel', { name: 'Achievements' })).toBeInTheDocument(),
{ timeout: 3000 },
);
expect(screen.getByRole('tab', { name: 'Achievements' })).toHaveAttribute(
'aria-selected',
Expand All @@ -58,8 +93,9 @@ describe('ProfileTabs', () => {
renderWithTheme(<ProfileTabs />);
await user.click(screen.getByRole('tab', { name: 'Certification Program' }));

await waitFor(() =>
expect(screen.getByRole('tabpanel', { name: 'Certification Program' })).toBeInTheDocument(),
await waitFor(
() => expect(screen.getByRole('tabpanel', { name: 'Certification Program' })).toBeInTheDocument(),
{ timeout: 3000 },
);
expect(screen.getByRole('tab', { name: 'Certification Program' })).toHaveAttribute(
'aria-selected',
Expand Down
Loading
Loading