SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
import ROUTES from 'constants/routes';
import { navigate } from 'lib/router/navigation';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { ErrorV2 } from 'types/api';
import { Info } from 'types/api/v1/version/get';
import { SessionsContext } from 'types/api/v2/sessions/context/get';
import { Token } from 'types/api/v2/sessions/email_password/post';
import Login from '../index';
const VERSION_ENDPOINT = '*/api/v1/version';
const SESSIONS_CONTEXT_ENDPOINT = '*/api/v2/sessions/context';
const CALLBACK_AUTHN_ORG = 'callback_authn_org';
const CALLBACK_AUTHN_URL = 'https://sso.example.com/auth';
const PASSWORD_AUTHN_ORG = 'password_authn_org';
const PASSWORD_AUTHN_EMAIL = '[email protected]';
jest.mock('lib/router/navigation', () => ({
...jest.requireActual('lib/router/navigation'),
navigate: jest.fn(),
}));
const mockNavigate = navigate as jest.MockedFunction<typeof navigate>;
// Mock data
const mockVersionSetupCompleted: Info = {
setupCompleted: true,
ee: 'Y',
version: '0.25.0',
};
const mockVersionSetupIncomplete: Info = {
setupCompleted: false,
ee: 'Y',
version: '0.25.0',
};
const mockSingleOrgPasswordAuth: SessionsContext = {
exists: true,
orgs: [
{
id: 'org-1',
name: 'Test Organization',
authNSupport: {
password: [{ provider: 'email_password' }],
callback: [],
},
},
],
};
const mockSingleOrgCallbackAuth: SessionsContext = {
exists: true,
orgs: [
{
id: 'org-1',
name: 'Test Organization',
authNSupport: {
password: [],
callback: [{ provider: 'google', url: CALLBACK_AUTHN_URL }],
},
},
],
};
const mockMultiOrgMixedAuth: SessionsContext = {
exists: true,
orgs: [
{
id: 'org-1',
name: PASSWORD_AUTHN_ORG,
authNSupport: {
password: [{ provider: 'email_password' }],
callback: [],
},
},
{
id: 'org-2',
name: CALLBACK_AUTHN_ORG,
authNSupport: {
password: [],
callback: [{ provider: 'google', url: CALLBACK_AUTHN_URL }],
},
},
],
};
const mockOrgWithWarning: SessionsContext = {
exists: true,
orgs: [
{
id: 'org-1',
name: 'Warning Organization',
authNSupport: {
password: [{ provider: 'email_password' }],
callback: [],
},
warning: {
code: 'ORG_WARNING',
message: 'Organization has limited access',
url: 'https://example.com/warning',
errors: [{ message: 'Contact admin for full access' }],
} as ErrorV2,
},
],
};
const mockEmailPasswordResponse: Token = {
accessToken: 'mock-access-token',
refreshToken: 'mock-refresh-token',
};
describe('Login Component', () => {
beforeEach(() => {
jest.clearAllMocks();
server.use(
rest.get(VERSION_ENDPOINT, (_, res, ctx) =>
res(
ctx.status(200),
ctx.json({ data: mockVersionSetupCompleted, status: 'success' }),
),
),
);
});
afterEach(() => {
server.resetHandlers();
});
describe('Initial Render', () => {
it('renders login form with email input and next button', () => {
const { getByTestId, getByPlaceholderText } = render(<Login />);
expect(
screen.getByText(/sign in to monitor, trace, and troubleshoot/i),
).toBeInTheDocument();
expect(getByTestId('email')).toBeInTheDocument();
expect(getByTestId('initiate_login')).toBeInTheDocument();
expect(getByPlaceholderText('e.g. [email protected]')).toBeInTheDocument();
});
it('shows loading state when version data is being fetched', () => {
server.use(
rest.get(VERSION_ENDPOINT, (_, res, ctx) =>
res(
ctx.delay(100),
ctx.status(200),
ctx.json({ data: mockVersionSetupCompleted, status: 'success' }),
),
),
);
const { getByTestId } = render(<Login />);
expect(getByTestId('initiate_login')).toHaveAttribute(
'aria-disabled',
'true',
);
});
});
describe('Setup Check', () => {
it('redirects to signup when setup is not completed', async () => {
server.use(
rest.get(VERSION_ENDPOINT, (_, res, ctx) =>
res(
ctx.status(200),
ctx.json({ data: mockVersionSetupIncomplete, status: 'success' }),
),
),
);
render(<Login />);
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SIGN_UP);
});
});
it('stays on login page when setup is completed', async () => {
render(<Login />);
await waitFor(() => {
expect(mockNavigate).not.toHaveBeenCalled();
});
});
it('handles version API error gracefully', async () => {
server.use(
rest.get(VERSION_ENDPOINT, (req, res, ctx) =>
res(ctx.status(500), ctx.json({ error: 'Server error' })),
),
);
render(<Login />);
await waitFor(() => {
expect(mockNavigate).not.toHaveBeenCalled();
});
});
});
describe('Session Context Fetching', () => {
it('fetches session context on next button click and enables password', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
),
);
const { getByTestId } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
expect(getByTestId('password')).toBeInTheDocument();
});
});
it('handles session context API errors', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(
ctx.status(500),
ctx.json({
error: {
code: 'internal_server',
message: 'couldnt fetch the sessions context',
url: '',
},
}),
),
),
);
const { getByTestId, getByText } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
expect(getByText('couldnt fetch the sessions context')).toBeInTheDocument();
});
});
it('auto-selects organization when only one exists', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (req, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
),
);
const { getByTestId } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
// Should show password field directly (no org selection needed)
expect(getByTestId('password')).toBeInTheDocument();
expect(screen.queryByText(/organization name/i)).not.toBeInTheDocument();
});
});
});
describe('Organization Selection', () => {
it('shows organization dropdown when multiple orgs exist', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockMultiOrgMixedAuth })),
),
);
const { getByTestId, getByText } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
expect(getByText('Organization Name')).toBeInTheDocument();
});
await screen.findByRole('combobox');
// Click on the dropdown to reveal the options
await user.click(screen.getByRole('combobox'));
await waitFor(() => {
expect(screen.getByText(PASSWORD_AUTHN_ORG)).toBeInTheDocument();
expect(screen.getByText(CALLBACK_AUTHN_ORG)).toBeInTheDocument();
});
});
it('updates selected organization on dropdown change', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (req, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockMultiOrgMixedAuth })),
),
);
render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = screen.getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = screen.getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await screen.findByRole('combobox');
// Select CALLBACK_AUTHN_ORG
await user.click(screen.getByRole('combobox'));
await user.click(screen.getByText(CALLBACK_AUTHN_ORG));
await screen.findByRole('button', { name: /sign in with sso/i });
});
});
describe('Password Authentication', () => {
it('shows password field when password auth is supported', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
),
);
const { getByTestId, getByText } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
expect(getByTestId('password')).toBeInTheDocument();
expect(getByText(/forgot password/i)).toBeInTheDocument();
expect(getByTestId('password_authn_submit')).toBeInTheDocument();
});
});
it('enables password auth when URL parameter password=Y', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgCallbackAuth })),
),
);
const { getByTestId } = render(<Login />, undefined, {
initialRoute: '/login?password=Y',
});
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
// Should show password field even for SSO org due to password=Y override
expect(getByTestId('password')).toBeInTheDocument();
});
});
});
describe('Callback Authentication', () => {
const originalLocation = window.location;
// The redirect case swaps `window.location` for a stub. history@5 reads
// that object on every `history.location` access, so leaving the stub in
// place would freeze the URL for every later test in this file.
afterEach(() => {
Object.defineProperty(window, 'location', {
value: originalLocation,
writable: true,
configurable: true,
});
});
it('shows callback login button when callback auth is supported', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgCallbackAuth })),
),
);
const { getByTestId, queryByTestId } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
expect(getByTestId('callback_authn_submit')).toBeInTheDocument();
expect(queryByTestId('password')).not.toBeInTheDocument();
});
});
it('redirects to callback URL on button click', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
// Mock window.location.href. The rest of the shape matters: history@5
// re-reads `window.location` on every access, so a stub without a
// pathname breaks every later render in this file.
const mockLocation = {
href: 'http://localhost/',
origin: 'http://localhost',
pathname: '/',
search: '',
hash: '',
};
Object.defineProperty(window, 'location', {
value: mockLocation,
writable: true,
configurable: true,
});
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgCallbackAuth })),
),
);
const { getByTestId, queryByTestId } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
expect(getByTestId('callback_authn_submit')).toBeInTheDocument();
expect(queryByTestId('password')).not.toBeInTheDocument();
});
const callbackButton = getByTestId('callback_authn_submit');
await user.click(callbackButton);
// Check that window.location.href was set to the callback URL
await waitFor(() => {
expect(window.location.href).toBe(CALLBACK_AUTHN_URL);
});
});
});
describe('Password Authentication Execution', () => {
it('calls email/password API with correct parameters', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
),
rest.post('*/api/v2/sessions/email_password', async (_, res, ctx) =>
res(
ctx.status(200),
ctx.json({ status: 'success', data: mockEmailPasswordResponse }),
),
),
);
const { getByTestId } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
expect(getByTestId('password')).toBeInTheDocument();
});
const passwordInput = getByTestId('password');
const loginButton = getByTestId('password_authn_submit');
await user.type(passwordInput, 'testpassword');
await user.click(loginButton);
// do not test for the request paramters here. Reference: https://mswjs.io/docs/best-practices/avoid-request-assertions
// rather test for the effects of the request
await waitFor(() => {
expect(localStorage.getItem('AUTH_TOKEN')).toBe('mock-access-token');
});
});
it('shows error modal on authentication failure', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
),
rest.post('*/api/v2/sessions/email_password', (_, res, ctx) =>
res(
ctx.status(401),
ctx.json({
error: {
code: 'invalid_input',
message: 'invalid password',
url: '',
},
}),
),
),
);
const { getByTestId, getByText } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
expect(getByTestId('password')).toBeInTheDocument();
});
const passwordInput = getByTestId('password');
const loginButton = getByTestId('password_authn_submit');
await user.type(passwordInput, 'wrongpassword');
await user.click(loginButton);
await waitFor(() => {
expect(getByText('invalid password')).toBeInTheDocument();
});
});
});
describe('URL Parameter Handling', () => {
it('calls afterLogin when accessToken and refreshToken are in URL', async () => {
render(<Login />, undefined, {
initialRoute: '/login?accessToken=test-token&refreshToken=test-refresh',
});
await waitFor(() => {
expect(localStorage.getItem('AUTH_TOKEN')).toBe('test-token');
expect(localStorage.getItem('REFRESH_AUTH_TOKEN')).toBe('test-refresh');
});
});
it('shows error modal when callbackauthnerr parameter exists', async () => {
const { getByText } = render(<Login />, undefined, {
initialRoute:
'/login?callbackauthnerr=true&code=AUTH_ERROR&message=Authentication failed&url=https://example.com/error&errors=[{"message":"Invalid token"}]',
});
await waitFor(() => {
expect(getByText('Authentication failed')).toBeInTheDocument();
});
});
it('handles malformed error JSON gracefully', async () => {
const { queryByText, getByText } = render(<Login />, undefined, {
initialRoute:
'/login?callbackauthnerr=true&code=AUTH_ERROR&message=Authentication failed&errors=invalid-json',
});
await waitFor(() => {
expect(queryByText('invalid-json')).not.toBeInTheDocument();
expect(getByText('Authentication failed')).toBeInTheDocument();
});
});
});
describe('Session Organization Warnings', () => {
it('shows warning modal when org has warning', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (req, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockOrgWithWarning })),
),
);
render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = screen.getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = screen.getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
expect(
screen.getByText(/organization has limited access/i),
).toBeInTheDocument();
});
});
it('shows warning modal when a warning org is selected among multiple orgs', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
// Mock multiple orgs including one with a warning
const mockMultiOrgWithWarning = {
orgs: [
{ id: 'org1', name: 'Org 1' },
{
id: 'org2',
name: 'Org 2',
warning: {
code: 'ORG_WARNING',
message: 'Organization has limited access',
url: 'https://example.com/warning',
errors: [{ message: 'Contact admin for full access' }],
} as ErrorV2,
},
],
};
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockMultiOrgWithWarning })),
),
);
const { getByTestId } = render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await screen.findByRole('combobox');
// Select the organization with a warning
await user.click(screen.getByRole('combobox'));
await user.click(screen.getByText('Org 2'));
await waitFor(() => {
expect(
screen.getByText(/organization has limited access/i),
).toBeInTheDocument();
});
});
});
describe('Form State Management', () => {
it('disables form fields during loading states', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (req, res, ctx) =>
res(
ctx.delay(100),
ctx.status(200),
ctx.json({ data: mockSingleOrgPasswordAuth }),
),
),
);
render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = screen.getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = screen.getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
// Button should be disabled during API call
expect(nextButton).toHaveAttribute('aria-disabled', 'true');
});
it('shows correct button text for each auth method', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (req, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
),
);
render(<Login />);
// Initially shows "Next" button
expect(screen.getByTestId('initiate_login')).toBeInTheDocument();
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = screen.getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = screen.getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
// Should show "Sign in with Password" button for password auth
expect(screen.getByTestId('password_authn_submit')).toBeInTheDocument();
expect(screen.queryByTestId('initiate_login')).not.toBeInTheDocument();
});
});
});
describe('Edge Cases', () => {
it('handles user with no organizations', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockNoOrgs: SessionsContext = {
exists: false,
orgs: [],
};
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (req, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockNoOrgs })),
),
);
render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = screen.getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = screen.getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
// Should not show any auth method buttons
expect(
screen.queryByTestId('password_authn_submit'),
).not.toBeInTheDocument();
expect(
screen.queryByTestId('callback_authn_submit'),
).not.toBeInTheDocument();
});
});
it('handles organization with no auth support', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockNoAuthSupport: SessionsContext = {
exists: true,
orgs: [
{
id: 'org-1',
name: 'No Auth Organization',
authNSupport: {
password: [],
callback: [],
},
},
],
};
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (req, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockNoAuthSupport })),
),
);
render(<Login />);
// Wait for version API to complete (email input becomes enabled)
const emailInput = await waitFor(() => {
const input = screen.getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, PASSWORD_AUTHN_EMAIL);
const nextButton = await waitFor(() => {
const button = screen.getByTestId('initiate_login');
expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
});
await user.click(nextButton);
await waitFor(() => {
// Should not show any auth method buttons
expect(
screen.queryByTestId('password_authn_submit'),
).not.toBeInTheDocument();
expect(
screen.queryByTestId('callback_authn_submit'),
).not.toBeInTheDocument();
});
});
});
describe('Enter key submission', () => {
const EMAIL_PASSWORD_ENDPOINT = '*/api/v2/sessions/email_password';
async function typeEmail(
user: ReturnType<typeof userEvent.setup>,
email: string,
): Promise<HTMLElement> {
const emailInput = await waitFor(() => {
const input = screen.getByTestId('email');
expect(input).not.toBeDisabled();
return input;
});
await user.type(emailInput, email);
return emailInput;
}
it('fetches the sessions context once on Enter in the email field', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
let contextCalls = 0;
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) => {
contextCalls += 1;
return res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth }));
}),
);
render(<Login />);
await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
await screen.findByTestId('password');
expect(contextCalls).toBe(1);
});
// Bug: the email onPressEnter calls onNextHandler without checking isEmailValid (container/Login/index.tsx:329).
it.skip('does not fetch the sessions context on Enter with an invalid email', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
let contextCalls = 0;
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) => {
contextCalls += 1;
return res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth }));
}),
);
render(<Login />);
await typeEmail(user, 'not-an-email');
expect(screen.getByTestId('initiate_login')).toHaveAttribute(
'aria-disabled',
'true',
);
await user.keyboard('{enter}');
await new Promise((resolve) => setTimeout(resolve, 50));
expect(contextCalls).toBe(0);
});
it('signs in once on Enter in the password field', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
let loginCalls = 0;
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
),
rest.post(EMAIL_PASSWORD_ENDPOINT, (_, res, ctx) => {
loginCalls += 1;
return res(
ctx.status(200),
ctx.json({ status: 'success', data: mockEmailPasswordResponse }),
);
}),
);
render(<Login />);
await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
await user.type(
await screen.findByTestId('password'),
'testpassword{enter}',
);
await waitFor(() => {
expect(localStorage.getItem('AUTH_TOKEN')).toBe('mock-access-token');
});
expect(loginCalls).toBe(1);
});
it('does not sign in on Enter while the password is empty', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
let loginCalls = 0;
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
),
rest.post(EMAIL_PASSWORD_ENDPOINT, (_, res, ctx) => {
loginCalls += 1;
return res(
ctx.status(200),
ctx.json({ status: 'success', data: mockEmailPasswordResponse }),
);
}),
);
render(<Login />);
await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
const passwordInput = await screen.findByTestId('password');
expect(screen.getByTestId('password_authn_submit')).toHaveAttribute(
'aria-disabled',
'true',
);
await user.type(passwordInput, '{enter}');
// Give a wrongly sent request time to land before asserting it never did.
await new Promise((resolve) => setTimeout(resolve, 50));
expect(loginCalls).toBe(0);
});
it('does not sign in again on Enter while the first sign in is loading', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
let loginCalls = 0;
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
),
rest.post(EMAIL_PASSWORD_ENDPOINT, (_, res, ctx) => {
loginCalls += 1;
return res(
ctx.delay(1000),
ctx.status(200),
ctx.json({ status: 'success', data: mockEmailPasswordResponse }),
);
}),
);
render(<Login />);
const emailInput = await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
await user.type(
await screen.findByTestId('password'),
'testpassword{enter}',
);
const submitButton = screen.getByTestId('password_authn_submit');
await waitFor(() => {
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
});
// The password input is disabled while submitting; the email input is not.
await user.type(emailInput, '{enter}');
await waitFor(() => {
expect(localStorage.getItem('AUTH_TOKEN')).toBe('mock-access-token');
});
expect(loginCalls).toBe(1);
});
it('redirects to the SSO url on Enter for a callback org', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
Object.defineProperty(window, 'location', {
value: { href: 'http://localhost/' },
writable: true,
});
server.use(
rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockSingleOrgCallbackAuth })),
),
);
render(<Login />);
const emailInput = await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
await screen.findByTestId('callback_authn_submit');
await user.type(emailInput, '{enter}');
await waitFor(() => {
expect(window.location.href).toBe(CALLBACK_AUTHN_URL);
});
});
});
});