Skip to content
Closed
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
41 changes: 41 additions & 0 deletions react/e2e/fixtures/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/** Shapes match the live node-hnapi `/user/<id>` and feed responses (the user endpoint is mocked; it 404s live). */
export const USERS = {
pg: {
id: 'pg',
created_time: 1160418092,
created: '20 years ago',
karma: 157316,
avg: null,
about: 'Bug fixer. <a href="https://paulgraham.com">paulgraham.com</a><script>window.__xss = true</script>',
},
dang: {
id: 'dang',
created_time: 1191529364,
created: '19 years ago',
karma: 30000,
avg: null,
},
dhouston: {
id: 'dhouston',
created_time: 1175714200,
created: '19 years ago',
karma: 8642,
avg: null,
about: 'Founder of Dropbox.',
},
} as const;

export const NEWS_FEED = [
{
id: 8863,
title: 'My YC app: Dropbox - Throw away your USB drive',
points: 104,
user: 'dhouston',
time: 1175714200,
time_ago: '19 years ago',
comments_count: 71,
type: 'link',
url: 'http://www.getdropbox.com/u/2/screencast.html',
domain: 'getdropbox.com',
},
];
90 changes: 90 additions & 0 deletions react/e2e/user.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { expect, test } from '@playwright/test';
import type { Page } from '@playwright/test';
import { mockHnApi } from './support/mock-api';
import { NEWS_FEED, USERS } from './fixtures/user';

async function mockUsers(page: Page) {
await mockHnApi(page, {
'/news': () => NEWS_FEED,
'/user/': (url) => {
const id = decodeURIComponent(url.pathname.slice('/user/'.length));
return USERS[id as keyof typeof USERS] ?? { error: 'unknown user' };
},
});
}

test.describe('user profile', () => {
test('/user/:id renders id, karma, created and sanitized about', async ({ page }) => {
await mockUsers(page);
await page.goto('/user/pg');
const profile = page.getByTestId('user-profile');
await expect(profile).toHaveAttribute('data-user-id', 'pg');
await expect(profile.locator('.main-details .name')).toHaveText('pg');
await expect(profile.locator('.main-details .right')).toHaveText('157316 ★');
await expect(profile.locator('.main-details .age')).toHaveText('Created 20 years ago');
const about = profile.locator('.other-details p');
await expect(about).toContainText('Bug fixer.');
await expect(about.getByRole('link', { name: 'paulgraham.com' })).toHaveAttribute(
'href',
'https://paulgraham.com'
);
await expect(about.locator('script')).toHaveCount(0);
expect(await page.evaluate(() => (window as unknown as { __xss?: boolean }).__xss)).toBeUndefined();
// Desktop viewport hides the mobile header.
await expect(profile.locator('.item-header')).toBeHidden();
});

test('omits the about section when the user has none', async ({ page }) => {
await mockUsers(page);
await page.goto('/user/dang');
await expect(page.locator('.main-details .right')).toHaveText('30000 ★');
await expect(page.locator('.other-details')).toHaveCount(0);
});

test('shows the error state when the user cannot be loaded', async ({ page }) => {
await mockHnApi(page, {});
await page.goto('/user/nobody');
await expect(page.getByRole('alert')).toContainText('Could not load user nobody.');
await expect(page.getByTestId('user-profile')).toHaveAttribute('data-user-id', 'nobody');
});

test('client-side navigation from the feed to a user and back', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 812 });
await mockUsers(page);
await page.goto('/news/1');
await expect(page.getByTestId('feed')).toBeVisible();

const userLink = page.locator('a[href="/user/dhouston"]');
// The feed list lands in a parallel phase; fall back to an in-app history navigation until it renders user links.
if ((await userLink.count()) > 0) {
await userLink.first().click();
} else {
await page.evaluate(() => {
window.history.pushState({}, '', '/user/pg');
window.dispatchEvent(new PopStateEvent('popstate'));
});
}
const profile = page.getByTestId('user-profile');
await expect(profile.locator('.main-details .name')).toBeVisible();
const id = await profile.getAttribute('data-user-id');
await expect(profile.locator('.item-header')).toContainText(`Profile: ${id}`);

const back = page.getByRole('button', { name: 'Go back' });
await back.focus();
await page.keyboard.press('Enter');
await expect(page).toHaveURL(/\/news\/1$/);
await expect(page.getByTestId('feed')).toBeVisible();
});

test('changing the user id in-app refetches the profile', async ({ page }) => {
await mockUsers(page);
await page.goto('/user/pg');
await expect(page.locator('.main-details .name')).toHaveText('pg');
await page.evaluate(() => {
window.history.pushState({}, '', '/user/dang');
window.dispatchEvent(new PopStateEvent('popstate'));
});
await expect(page.locator('.main-details .name')).toHaveText('dang');
await expect(page.locator('.main-details .right')).toHaveText('30000 ★');
});
});
85 changes: 85 additions & 0 deletions react/src/user/UserProfile.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
@use '../styles/media' as *;

.profile {
padding: 30px;

pre {
white-space: pre-wrap;
}

@media #{$mobile-only} {
padding: 110px 15px 0 15px;

.title-block {
font-size: 15px;
text-align: center;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
margin: 0 75px;
}

.back-button {
position: absolute;
top: 52%;
width: 0.6rem;
height: 0.6rem;
background: transparent;
box-shadow: 0 0 0 lightgray;
transition: all 200ms ease;
left: 4%;
transform: translate3d(0, -50%, 0) rotate(-135deg);
cursor: pointer;
}

.item-header {
background-color: #fff;
padding: 10px 0 10px 0;
position: fixed;
width: 100%;
left: 0;
top: 62px;
height: 20px;
}
}

@media #{$laptop-only} {
.mobile {
display: none;
}
}

.main-details {
.name {
font-weight: bold;
font-size: 32px;
letter-spacing: 2px;
}

.age {
font-weight: bold;
color: #696969;
padding-bottom: 0;
}

.right {
float: right;
font-weight: bold;
font-size: 32px;
letter-spacing: 2px;
}

@media #{$mobile-only} {
margin-top: 20px;

.name,
.right {
font-size: 18px;
}
}
}

.other-details {
word-wrap: break-word;
}
}
173 changes: 173 additions & 0 deletions react/src/user/UserProfile.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Link, Route, Routes } from 'react-router-dom';
import { vi } from 'vitest';
import type { User } from '../shared/models';
import { fetchUser } from '../shared/services/hackernewsApi';
import { renderWithProviders } from '../test/renderWithProviders';
import UserProfile from './UserProfile';

vi.mock('../shared/services/hackernewsApi');

const mockFetchUser = vi.mocked(fetchUser);

const pg: User = {
id: 'pg',
created: '19 years ago',
karma: 157316,
avg: 4.2,
about: 'Bug fixer. <a href="https://paulgraham.com">paulgraham.com</a>',
};

function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}

function renderProfile(route = '/user/pg') {
return renderWithProviders(
<>
<Routes>
<Route path="/user/:id" element={<UserProfile />} />
<Route path="/news/1" element={<Link to="/user/pg">open pg</Link>} />
</Routes>
<Link to="/user/dang">dang</Link>
</>,
{ route }
);
}

describe('UserProfile', () => {
it('shows the loader while loading and keeps the root data attributes', () => {
mockFetchUser.mockReturnValue(new Promise(() => {}));
renderProfile();
expect(screen.getByRole('status')).toHaveTextContent('Loading...');
const root = screen.getByTestId('user-profile');
expect(root).toHaveAttribute('data-user-id', 'pg');
expect(mockFetchUser).toHaveBeenCalledWith('pg', expect.any(AbortSignal));
expect(root.querySelector('.profile')).toBeNull();
});

it('renders the loaded profile with about', async () => {
mockFetchUser.mockResolvedValue(pg);
renderProfile();
const root = screen.getByTestId('user-profile');
await waitFor(() => expect(root.querySelector('.profile')).not.toBeNull());
expect(screen.queryByRole('status')).toBeNull();
expect(root.querySelector('.item-header.mobile .title-block')).toHaveTextContent('Profile: pg');
expect(root.querySelector('.main-details .name')).toHaveTextContent('pg');
expect(root.querySelector('.main-details .right')).toHaveTextContent('157316 ★');
expect(root.querySelector('.main-details .age')).toHaveTextContent('Created 19 years ago');
const about = root.querySelector('.other-details p')!;
expect(about).toHaveTextContent('Bug fixer. paulgraham.com');
expect(about.querySelector('a')).toHaveAttribute('href', 'https://paulgraham.com');
expect(root).toHaveAttribute('data-user-id', 'pg');
});

it('omits other-details when the user has no about', async () => {
mockFetchUser.mockResolvedValue({ ...pg, about: undefined });
renderProfile();
await screen.findByText('Created 19 years ago');
expect(screen.getByTestId('user-profile').querySelector('.other-details')).toBeNull();
});

it('sanitizes the about html', async () => {
mockFetchUser.mockResolvedValue({
...pg,
about: '<img src="x" onerror="alert(1)"><script>alert(2)</script>hi',
});
renderProfile();
await screen.findByText('hi');
const about = screen.getByTestId('user-profile').querySelector('.other-details p')!;
expect(about.innerHTML).not.toMatch(/script|onerror/);
});

it('shows the error message when loading fails', async () => {
mockFetchUser.mockRejectedValue(new Error('HN API request failed with status 404'));
renderProfile();
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('Could not load user pg.');
expect(screen.queryByRole('status')).toBeNull();
expect(screen.getByTestId('user-profile')).toHaveAttribute('data-user-id', 'pg');
});

it('ignores AbortError rejections', async () => {
mockFetchUser.mockRejectedValue(new DOMException('aborted', 'AbortError'));
renderProfile();
await act(async () => {});
expect(screen.queryByRole('alert')).toBeNull();
expect(screen.getByRole('status')).toBeInTheDocument();
});

it('navigates back on click and via keyboard', async () => {
mockFetchUser.mockResolvedValue(pg);
renderProfile('/news/1');
const user = userEvent.setup();

await user.click(screen.getByRole('link', { name: 'open pg' }));
const back = await screen.findByRole('button', { name: 'Go back' });
expect(back).toHaveClass('back-button');
expect(back).toHaveAttribute('tabindex', '0');
await user.click(back);
expect(screen.getByTestId('location')).toHaveTextContent('/news/1');

await user.click(screen.getByRole('link', { name: 'open pg' }));
(await screen.findByRole('button', { name: 'Go back' })).focus();
await user.keyboard('{Enter}');
expect(screen.getByTestId('location')).toHaveTextContent('/news/1');

await user.click(screen.getByRole('link', { name: 'open pg' }));
(await screen.findByRole('button', { name: 'Go back' })).focus();
await user.keyboard(' ');
expect(screen.getByTestId('location')).toHaveTextContent('/news/1');

await user.click(screen.getByRole('link', { name: 'open pg' }));
fireEvent.keyDown(await screen.findByRole('button', { name: 'Go back' }), { key: 'a' });
expect(screen.getByTestId('location')).toHaveTextContent('/user/pg');
});

it('aborts and refetches when the id changes, ignoring the stale response', async () => {
const first = deferred<User>();
const second = deferred<User>();
mockFetchUser.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
renderProfile();
const firstSignal = mockFetchUser.mock.calls[0][1]!;
expect(firstSignal.aborted).toBe(false);

await userEvent.setup().click(screen.getByRole('link', { name: 'dang' }));
expect(firstSignal.aborted).toBe(true);
expect(mockFetchUser).toHaveBeenLastCalledWith('dang', expect.any(AbortSignal));
expect(screen.getByTestId('user-profile')).toHaveAttribute('data-user-id', 'dang');

await act(async () => first.resolve(pg));
expect(screen.getByRole('status')).toBeInTheDocument();
expect(screen.queryByText('Created 19 years ago')).toBeNull();

await act(async () => second.resolve({ id: 'dang', created: '16 years ago', karma: 30000 }));
expect(screen.getByText('Profile: dang')).toBeInTheDocument();
expect(screen.getByText('30000 ★')).toBeInTheDocument();
});

it('does not show an error for a request rejected after the id changed', async () => {
const first = deferred<User>();
mockFetchUser.mockReturnValueOnce(first.promise).mockResolvedValueOnce({ ...pg, id: 'dang' });
renderProfile();
await userEvent.setup().click(screen.getByRole('link', { name: 'dang' }));
await act(async () => first.reject(new Error('network down')));
expect(screen.queryByRole('alert')).toBeNull();
expect(await screen.findByText('Profile: dang')).toBeInTheDocument();
});

it('aborts the request on unmount', () => {
mockFetchUser.mockReturnValue(new Promise(() => {}));
const { unmount } = renderProfile();
const signal = mockFetchUser.mock.calls[0][1]!;
unmount();
expect(signal.aborted).toBe(true);
});
});
Loading
Loading