Skip to content

Commit 6831dc8

Browse files
committed
test(ui): pin the invitation preview on the login and register pages, found / 404 / failure (wip)
Claude-Session: https://claude.ai/code/session_01SMps7wq7rBTk53e8KTSEup Co-authored-by: Claude <noreply@anthropic.com>
1 parent b00d5fb commit 6831dc8

5 files changed

Lines changed: 479 additions & 2 deletions

File tree

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
/**
2+
* #26473 — the console's own `/login` and `/register`, opened signed out from
3+
* an invitation link, greet the visitor by WHO invited them and to WHAT.
4+
*
5+
* The read is app-shell's `useInvitationPreview` over the server's signed-out
6+
* `GET {authUrl}/organization/invitation-preview?id=ID`; the package's default
7+
* pages carry the same pins in
8+
* `packages/app-shell/src/console/auth/__tests__/invitationPreview-26473.test.tsx`.
9+
* Pinned here for the pages the console actually routes:
10+
*
11+
* - found: the card names the inviter and the organization and shows the
12+
* MASKED address as the one to use; the email field stays empty;
13+
* - 404: today's generic invitation copy;
14+
* - a failed read: today's generic copy too, and the form still renders.
15+
*
16+
* Rendered with a real `AuthProvider` over a real `createAuthClient`; only
17+
* `fetch` is a stub. Generic copy is read from the en pack.
18+
*/
19+
20+
import '@testing-library/jest-dom/vitest';
21+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
22+
import { act, render, screen, cleanup, waitFor } from '@testing-library/react';
23+
import { MemoryRouter, Routes, Route } from 'react-router-dom';
24+
import { I18nProvider } from '@object-ui/i18n';
25+
import { builtInLocales } from '@object-ui/i18n/locales';
26+
import { AuthProvider, createAuthClient } from '@object-ui/auth';
27+
import type { AuthPublicConfig } from '@object-ui/auth';
28+
import { LoginPage } from '../LoginPage';
29+
import { RegisterPage } from '../RegisterPage';
30+
31+
const AUTH_URL = 'http://localhost/api/v1/auth';
32+
const en = builtInLocales.en.auth;
33+
const INVITATION_ID = 'inv_26473';
34+
const INVITE_QUERY = `?redirect=${encodeURIComponent(`/accept-invitation/${INVITATION_ID}`)}`;
35+
const ORG = 'Xiaolin Decoration Studio';
36+
const INVITER = 'Lin Xiao';
37+
const MASKED = 'z***@example.com';
38+
const MASKED_TEXT = new RegExp(MASKED.replace(/[*.]/g, '\\$&'));
39+
40+
const CONFIG: AuthPublicConfig = {
41+
emailPassword: { enabled: true, disableSignUp: false, requireEmailVerification: false },
42+
features: { audiencePosture: 'invite_only' },
43+
};
44+
45+
type PreviewAnswer = 'found' | 404 | 500;
46+
let previewRequests: string[];
47+
48+
function stubServer(answer: PreviewAnswer): typeof fetch {
49+
previewRequests = [];
50+
const json = (body: unknown, status = 200) =>
51+
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
52+
return (async (input: string | URL | Request) => {
53+
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
54+
if (url.includes('/organization/invitation-preview')) {
55+
previewRequests.push(url);
56+
if (answer === 'found') {
57+
return json({ success: true, data: { organizationName: ORG, inviterName: INVITER, email: MASKED } });
58+
}
59+
return json(
60+
{
61+
success: false,
62+
error:
63+
answer === 404
64+
? { code: 'RESOURCE_NOT_FOUND', message: 'Invitation not found.' }
65+
: { code: 'INTERNAL_ERROR', message: 'The invitation preview is unavailable.' },
66+
},
67+
answer,
68+
);
69+
}
70+
if (url.endsWith('/bootstrap-status')) return json({ hasOwner: true });
71+
if (url.endsWith('/config')) return json({ success: true, data: CONFIG });
72+
return json(null);
73+
}) as typeof fetch;
74+
}
75+
76+
function renderAt(path: string, answer: PreviewAnswer) {
77+
const fetchFn = stubServer(answer);
78+
vi.stubGlobal('fetch', fetchFn);
79+
window.history.replaceState({}, '', path);
80+
const client = createAuthClient({ baseURL: AUTH_URL, fetchFn });
81+
return render(
82+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }} persistLanguage={false}>
83+
<AuthProvider authUrl={AUTH_URL} client={client}>
84+
<MemoryRouter initialEntries={[path]}>
85+
<Routes>
86+
<Route path="/login" element={<LoginPage />} />
87+
<Route path="/register" element={<RegisterPage />} />
88+
</Routes>
89+
</MemoryRouter>
90+
</AuthProvider>
91+
</I18nProvider>,
92+
);
93+
}
94+
95+
async function previewAnswered() {
96+
await waitFor(() => expect(previewRequests).toHaveLength(1));
97+
await act(async () => {
98+
await new Promise((resolve) => setTimeout(resolve, 0));
99+
});
100+
}
101+
102+
beforeEach(() => {
103+
window.localStorage.clear();
104+
vi.spyOn(console, 'warn').mockImplementation(() => {});
105+
});
106+
107+
afterEach(() => {
108+
cleanup();
109+
vi.unstubAllGlobals();
110+
vi.restoreAllMocks();
111+
window.history.replaceState({}, '', '/');
112+
});
113+
114+
describe('console /login — the invitation landing reads the signed-out preview (#26473)', () => {
115+
it('found: names the inviter and the organization, shows the masked address, prefills nothing', async () => {
116+
renderAt(`/login${INVITE_QUERY}`, 'found');
117+
118+
const heading = await screen.findByRole('heading', { name: new RegExp(ORG) });
119+
expect(heading).toHaveTextContent(INVITER);
120+
expect(screen.getByText(MASKED_TEXT)).toBeInTheDocument();
121+
expect(screen.queryByRole('heading', { name: en.login.invitationTitle })).toBeNull();
122+
expect(previewRequests).toEqual([`${AUTH_URL}/organization/invitation-preview?id=${INVITATION_ID}`]);
123+
expect(await screen.findByLabelText(en.login.emailLabel)).toHaveValue('');
124+
});
125+
126+
it('404: keeps the generic invitation copy', async () => {
127+
renderAt(`/login${INVITE_QUERY}`, 404);
128+
await previewAnswered();
129+
130+
expect(await screen.findByRole('heading', { name: en.login.invitationTitle })).toBeInTheDocument();
131+
expect(screen.queryByText(new RegExp(ORG))).toBeNull();
132+
});
133+
134+
it('a failed read: keeps the generic copy and the sign-in form', async () => {
135+
renderAt(`/login${INVITE_QUERY}`, 500);
136+
await previewAnswered();
137+
138+
expect(await screen.findByRole('heading', { name: en.login.invitationTitle })).toBeInTheDocument();
139+
expect(await screen.findByLabelText(en.login.emailLabel)).toBeInTheDocument();
140+
});
141+
});
142+
143+
describe('console /register — the sign-up step reads the same preview (#26473)', () => {
144+
it('found: names the inviter and the organization, shows the masked address, prefills nothing', async () => {
145+
renderAt(`/register${INVITE_QUERY}`, 'found');
146+
147+
const heading = await screen.findByRole('heading', { name: new RegExp(ORG) });
148+
expect(heading).toHaveTextContent(INVITER);
149+
expect(screen.getByText(MASKED_TEXT)).toBeInTheDocument();
150+
expect(screen.getByLabelText(en.register.emailLabel)).toHaveValue('');
151+
});
152+
153+
it('404: keeps the generic invitation copy', async () => {
154+
renderAt(`/register${INVITE_QUERY}`, 404);
155+
await previewAnswered();
156+
157+
expect(await screen.findByRole('heading', { name: en.register.invitationTitle })).toBeInTheDocument();
158+
});
159+
160+
it('a failed read: keeps the generic copy and the form', async () => {
161+
renderAt(`/register${INVITE_QUERY}`, 500);
162+
await previewAnswered();
163+
164+
expect(await screen.findByRole('heading', { name: en.register.invitationTitle })).toBeInTheDocument();
165+
expect(screen.getByLabelText(en.register.emailLabel)).toBeInTheDocument();
166+
});
167+
});
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* #26473 — a visitor who opens an invitation link signed out is greeted by
11+
* WHO invited them and to WHAT, on `DefaultLoginPage` and on the
12+
* `DefaultRegisterPage` it hands to.
13+
*
14+
* The server's signed-out read is `GET {authUrl}/organization/invitation-preview?id=ID`
15+
* (objectstack `plugin-auth` `invitation-preview.ts`): `{ success, data:
16+
* { organizationName, inviterName, email } }` with the address MASKED, and one
17+
* uniform 404 for any id that is not a pending, unexpired invitation. Three
18+
* outcomes are pinned here, each on both pages where it differs:
19+
*
20+
* - found: the card names the inviter and the organization, and shows the
21+
* masked address as the one to use, while the email field stays EMPTY — a
22+
* masked value is not an address and is never prefilled;
23+
* - 404: today's generic invitation copy;
24+
* - a failed read (5xx, a network failure, a body of the wrong shape):
25+
* today's generic copy too, and the page keeps working.
26+
*
27+
* Rendered as shipped, like `defaultPagesFollowPosture-11705.test.tsx` beside
28+
* this file: the exported pages, `@object-ui/auth`'s real forms, a real
29+
* `AuthProvider` over a real `createAuthClient` and a real `I18nProvider`;
30+
* only `fetch` is a stub. Generic copy is read from the en pack.
31+
*/
32+
33+
import '@testing-library/jest-dom/vitest';
34+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
35+
import { act, render, screen, cleanup, waitFor } from '@testing-library/react';
36+
import { MemoryRouter, Routes, Route } from 'react-router-dom';
37+
import { I18nProvider } from '@object-ui/i18n';
38+
import { builtInLocales } from '@object-ui/i18n/locales';
39+
import { AuthProvider, createAuthClient } from '@object-ui/auth';
40+
import type { AuthPublicConfig } from '@object-ui/auth';
41+
import { LoginPage } from '../LoginPage';
42+
import { RegisterPage } from '../RegisterPage';
43+
44+
const AUTH_URL = 'http://localhost/api/v1/auth';
45+
const en = builtInLocales.en.auth;
46+
const INVITATION_ID = 'inv_26473';
47+
const INVITE_QUERY = `?redirect=${encodeURIComponent(`/accept-invitation/${INVITATION_ID}`)}`;
48+
const ORG = 'Xiaolin Decoration Studio';
49+
const INVITER = 'Lin Xiao';
50+
const MASKED = 'z***@example.com';
51+
52+
const CONFIG: AuthPublicConfig = {
53+
emailPassword: { enabled: true, disableSignUp: false, requireEmailVerification: false },
54+
features: { audiencePosture: 'invite_only' },
55+
};
56+
57+
type PreviewAnswer = 'found' | 'found-no-inviter' | 404 | 500 | 'network' | 'wrong-shape';
58+
59+
let previewRequests: string[];
60+
61+
function stubServer(answer: PreviewAnswer): typeof fetch {
62+
previewRequests = [];
63+
const json = (body: unknown, status = 200) =>
64+
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
65+
return (async (input: string | URL | Request, init?: RequestInit) => {
66+
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
67+
if (url.includes('/organization/invitation-preview')) {
68+
previewRequests.push(`${init?.method ?? 'GET'} ${url}`);
69+
switch (answer) {
70+
case 'found':
71+
return json({ success: true, data: { organizationName: ORG, inviterName: INVITER, email: MASKED } });
72+
case 'found-no-inviter':
73+
return json({ success: true, data: { organizationName: ORG, inviterName: null, email: MASKED } });
74+
case 404:
75+
return json(
76+
{ success: false, error: { code: 'RESOURCE_NOT_FOUND', message: 'Invitation not found.' } },
77+
404,
78+
);
79+
case 500:
80+
return json(
81+
{ success: false, error: { code: 'INTERNAL_ERROR', message: 'The invitation preview is unavailable.' } },
82+
500,
83+
);
84+
case 'network':
85+
throw new TypeError('Failed to fetch');
86+
case 'wrong-shape':
87+
return json({ organizationName: ORG });
88+
}
89+
}
90+
if (url.endsWith('/bootstrap-status')) return json({ hasOwner: true });
91+
if (url.endsWith('/config')) return json({ success: true, data: CONFIG });
92+
return json(null);
93+
}) as typeof fetch;
94+
}
95+
96+
function renderAt(path: string, answer: PreviewAnswer) {
97+
const fetchFn = stubServer(answer);
98+
vi.stubGlobal('fetch', fetchFn);
99+
const client = createAuthClient({ baseURL: AUTH_URL, fetchFn });
100+
return render(
101+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }} persistLanguage={false}>
102+
<AuthProvider authUrl={AUTH_URL} client={client}>
103+
<MemoryRouter initialEntries={[path]}>
104+
<Routes>
105+
<Route path="/login" element={<LoginPage />} />
106+
<Route path="/register" element={<RegisterPage />} />
107+
</Routes>
108+
</MemoryRouter>
109+
</AuthProvider>
110+
</I18nProvider>,
111+
);
112+
}
113+
114+
/** The preview was asked for, and its answer had the chance to land. */
115+
async function previewAnswered() {
116+
await waitFor(() => expect(previewRequests).toHaveLength(1));
117+
await act(async () => {
118+
await new Promise((resolve) => setTimeout(resolve, 0));
119+
});
120+
}
121+
122+
beforeEach(() => {
123+
window.localStorage.clear();
124+
vi.spyOn(console, 'warn').mockImplementation(() => {});
125+
});
126+
127+
afterEach(() => {
128+
cleanup();
129+
vi.unstubAllGlobals();
130+
vi.restoreAllMocks();
131+
});
132+
133+
describe('DefaultLoginPage — the invitation landing reads the signed-out preview (#26473)', () => {
134+
it('found: names the inviter and the organization, and shows the masked address', async () => {
135+
renderAt(`/login${INVITE_QUERY}`, 'found');
136+
137+
const heading = await screen.findByRole('heading', { name: new RegExp(ORG) });
138+
expect(heading).toHaveTextContent(INVITER);
139+
expect(screen.getByText(new RegExp(MASKED.replace(/[*.]/g, '\\$&')))).toBeInTheDocument();
140+
expect(screen.queryByRole('heading', { name: en.login.invitationTitle })).toBeNull();
141+
// One anonymous read, by the id the link carries.
142+
expect(previewRequests).toEqual([
143+
`GET ${AUTH_URL}/organization/invitation-preview?id=${INVITATION_ID}`,
144+
]);
145+
// The masked value is a hint, never a prefill.
146+
expect(await screen.findByLabelText(en.login.emailLabel)).toHaveValue('');
147+
});
148+
149+
it('found without an inviter name: names the organization alone', async () => {
150+
renderAt(`/login${INVITE_QUERY}`, 'found-no-inviter');
151+
152+
const heading = await screen.findByRole('heading', { name: new RegExp(ORG) });
153+
expect(heading).not.toHaveTextContent('null');
154+
expect(screen.queryByRole('heading', { name: en.login.invitationTitle })).toBeNull();
155+
});
156+
157+
it('404: keeps the generic invitation copy', async () => {
158+
renderAt(`/login${INVITE_QUERY}`, 404);
159+
await previewAnswered();
160+
161+
expect(await screen.findByRole('heading', { name: en.login.invitationTitle })).toBeInTheDocument();
162+
expect(screen.getByText(en.login.invitationDescription)).toBeInTheDocument();
163+
expect(screen.queryByText(new RegExp(ORG))).toBeNull();
164+
});
165+
166+
it.each([500, 'network', 'wrong-shape'] as const)(
167+
'a failed read (%s): keeps the generic copy and the sign-in form',
168+
async (answer) => {
169+
renderAt(`/login${INVITE_QUERY}`, answer);
170+
await previewAnswered();
171+
172+
expect(await screen.findByRole('heading', { name: en.login.invitationTitle })).toBeInTheDocument();
173+
expect(await screen.findByLabelText(en.login.emailLabel)).toBeInTheDocument();
174+
expect(screen.queryByText(new RegExp(ORG))).toBeNull();
175+
},
176+
);
177+
178+
it('asks for no preview when the visitor did not come from an invitation', async () => {
179+
renderAt('/login', 'found');
180+
await screen.findByLabelText(en.login.emailLabel);
181+
await act(async () => {
182+
await new Promise((resolve) => setTimeout(resolve, 0));
183+
});
184+
185+
expect(previewRequests).toEqual([]);
186+
});
187+
});
188+
189+
describe('DefaultRegisterPage — the sign-up step reads the same preview (#26473)', () => {
190+
it('found: names the inviter and the organization, shows the masked address, prefills nothing', async () => {
191+
renderAt(`/register${INVITE_QUERY}`, 'found');
192+
193+
const heading = await screen.findByRole('heading', { name: new RegExp(ORG) });
194+
expect(heading).toHaveTextContent(INVITER);
195+
expect(screen.getByText(new RegExp(MASKED.replace(/[*.]/g, '\\$&')))).toBeInTheDocument();
196+
expect(screen.queryByRole('heading', { name: en.register.invitationTitle })).toBeNull();
197+
expect(screen.getByLabelText(en.register.emailLabel)).toHaveValue('');
198+
});
199+
200+
it('404: keeps the generic invitation copy', async () => {
201+
renderAt(`/register${INVITE_QUERY}`, 404);
202+
await previewAnswered();
203+
204+
expect(await screen.findByRole('heading', { name: en.register.invitationTitle })).toBeInTheDocument();
205+
expect(screen.getByText(en.register.invitationDescription)).toBeInTheDocument();
206+
});
207+
208+
it('a failed read: keeps the generic copy and the form', async () => {
209+
renderAt(`/register${INVITE_QUERY}`, 500);
210+
await previewAnswered();
211+
212+
expect(await screen.findByRole('heading', { name: en.register.invitationTitle })).toBeInTheDocument();
213+
expect(screen.getByLabelText(en.register.emailLabel)).toBeInTheDocument();
214+
});
215+
});

0 commit comments

Comments
 (0)