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
137 changes: 137 additions & 0 deletions website/__tests__/profile.integration.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import AccountPage, { getStaticProps } from '~/pages/[handle]'

const mocks = vi.hoisted(() => ({
account: vi.fn(),
organization: vi.fn(),
user: undefined as { id: string } | undefined,
organizations: [] as { handle: string }[],
}))

vi.mock('~/lib/supabase', () => ({
default: {
rpc: (name: string) => {
const query = {
abortSignal: () => query,
maybeSingle: () =>
name === 'get_account' ? mocks.account() : mocks.organization(),
}
return query
},
},
}))
vi.mock('~/lib/avatars', () => ({
DEFAULT_AVATAR_SRC_URL: '/avatar.png',
getAvatarUrl: () => '/avatar.png',
}))
vi.mock('~/lib/auth', () => ({ useUser: () => mocks.user }))
vi.mock('next/router', () => ({
useRouter: () => ({ query: { handle: 'alice' }, push: vi.fn() }),
}))
vi.mock('next/head', () => ({ default: () => null }))
vi.mock('~/components/layouts/Layout', () => ({
default: ({ children }: { children: React.ReactNode }) => children,
}))
vi.mock('~/components/packages/PackageCard', () => ({ default: () => null }))
vi.mock('~/data/static-path-queries', () => ({ getAllProfiles: vi.fn() }))
vi.mock('~/data/packages/packages-query', () => ({
prefetchPackages: async () => {},
usePackagesQuery: () => ({ data: [], isSuccess: true }),
}))
vi.mock('~/data/organizations/users-organizations-query', () => ({
useUsersOrganizationsQuery: () => ({ data: mocks.organizations }),
}))

const profile = {
id: 'alice-id',
handle: 'alice',
display_name: 'Alice',
avatar_path: null,
bio: 'Postgres developer',
created_at: '2023-01-01T00:00:00Z',
}

describe('Profile pages', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.user = undefined
mocks.organizations = []
mocks.account.mockResolvedValue({ data: null, error: null })
mocks.organization.mockResolvedValue({ data: null, error: null })
})

it('returns a revalidated 404 for an unknown account or organization', async () => {
const result = await getStaticProps({ params: { handle: 'missing' } })

expect(result).toEqual({ notFound: true, revalidate: 300 })
})

it.each(['account', 'organization'] as const)(
'dehydrates an existing %s for the initial render',
async (type) => {
mocks[type].mockResolvedValue({ data: profile, error: null })

const result = await getStaticProps({ params: { handle: 'alice' } })

expect(result).toMatchObject({
props: {
dehydratedState: {
queries: [
{
queryKey: ['profile', 'alice'],
state: { data: { ...profile, type } },
},
],
},
},
revalidate: 300,
})
}
)

it('does not turn an API failure into a missing-profile response', async () => {
const error = new Error('Database unavailable')
mocks.account.mockResolvedValue({ data: null, error })

await expect(getStaticProps({ params: { handle: 'alice' } })).rejects.toBe(
error
)
})

it('hides Edit profile while an anonymous visitor has no profile data', () => {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
mocks.account.mockReturnValue(new Promise(() => {}))

render(
<QueryClientProvider client={client}>
<AccountPage />
</QueryClientProvider>
)

expect(screen.queryByRole('button', { name: 'Edit profile' })).toBeNull()
client.clear()
})

it.each(['owner', 'organization member'])(
'allows the %s to edit',
(viewer) => {
const client = new QueryClient()
client.setQueryData(['profile', 'alice'], profile)
mocks.user = { id: viewer === 'owner' ? profile.id : 'member-id' }
mocks.organizations = viewer === 'owner' ? [] : [{ handle: 'alice' }]

render(
<QueryClientProvider client={client}>
<AccountPage />
</QueryClientProvider>
)

expect(screen.getByRole('button', { name: 'Edit profile' })).toBeVisible()
client.clear()
}
)
})
10 changes: 7 additions & 3 deletions website/pages/[handle]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
prefetchPackages,
usePackagesQuery,
} from '~/data/packages/packages-query'
import { prefetchProfile, useProfileQuery } from '~/data/profiles/profile-query'
import { getProfile, useProfileQuery } from '~/data/profiles/profile-query'
import { getAllProfiles } from '~/data/static-path-queries'
import { NotFoundError } from '~/data/utils'
import { useUser } from '~/lib/auth'
Expand All @@ -32,7 +32,7 @@ const AccountPage: NextPageWithLayout = () => {
userId: user?.id,
})

const isUser = user?.id === profile?.id
const isUser = !!user && user.id === profile?.id
const isMember =
organizations?.find((org) => org.handle === handle) !== undefined

Expand Down Expand Up @@ -111,7 +111,11 @@ export const getStaticProps: GetStaticProps = async ({ params }) => {

try {
await Promise.all([
prefetchProfile(queryClient, { handle }),
// Unlike prefetchQuery, fetchQuery propagates errors to the 404 handler.
queryClient.fetchQuery({
queryKey: ['profile', handle],
queryFn: ({ signal }) => getProfile({ handle }, signal),
}),
prefetchPackages(queryClient, { handle }),
])
} catch (error) {
Expand Down