import { fireEvent, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { jsonResponse, renderUi } from '../../test/utils';
import { RegisterPage } from './RegisterPage';
afterEach(() => vi.restoreAllMocks());
const urlOf = (input: RequestInfo | URL) => (typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
function mockApi(registration: boolean, posts: unknown[]) {
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const req = input instanceof Request ? input : new Request(new URL(urlOf(input), 'http://localhost'), init);
if (req.url.endsWith('/api/auth/me')) return jsonResponse({ detail: 'not signed in', code: 'UNAUTHENTICATED' }, 401);
if (req.url.endsWith('/api/auth/config')) return jsonResponse({ provider: 'supabase', registration, new_account_role: 'viewer' });
if (req.url.endsWith('/api/auth/register')) { posts.push(await req.json()); return jsonResponse({ status: 'confirm_email', message: 'check' }); }
return jsonResponse({ ready: true, product_name: 'Astra' });
});
}
describe('register page', () => {
it('creates the account and tells the person to confirm the address', async () => {
const posts: unknown[] = [];
mockApi(true, posts);
renderUi(, { auth: true, route: '/register' });
fireEvent.change(await screen.findByLabelText(/Work e-mail/), { target: { value: 'priya@example.com' } });
fireEvent.change(screen.getByLabelText(/^Password/), { target: { value: 'Correct-Horse-9' } });
fireEvent.change(screen.getByLabelText(/Repeat the password/), { target: { value: 'Correct-Horse-8' } });
expect(screen.getByRole('button', { name: 'Create account' })).toBeDisabled(); // the two passwords differ
fireEvent.change(screen.getByLabelText(/Repeat the password/), { target: { value: 'Correct-Horse-9' } });
fireEvent.click(screen.getByRole('button', { name: 'Create account' }));
expect(await screen.findByTestId('register-sent')).toHaveTextContent('priya@example.com');
expect(posts).toEqual([{ email: 'priya@example.com', password: 'Correct-Horse-9' }]);
});
it('says so when sign-up is switched off', async () => {
mockApi(false, []);
renderUi(, { auth: true, route: '/register' });
await waitFor(() => expect(screen.getByText(/created by an administrator/)).toBeInTheDocument());
expect(screen.queryByRole('button', { name: 'Create account' })).toBeNull();
});
});