import { render, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import SilentLogin from './SilentLogin.component';
const { getOrThrow, getParseQueryStringFromLocation, loginAsync } = vi.hoisted(() => ({
getOrThrow: vi.fn(),
getParseQueryStringFromLocation: vi.fn(),
loginAsync: vi.fn(),
}));
vi.mock('@axa-fr/oidc-client', () => ({
OidcClient: { getOrThrow },
getParseQueryStringFromLocation,
}));
describe('silent login', () => {
beforeEach(() => {
vi.resetAllMocks();
loginAsync.mockResolvedValue(undefined);
getOrThrow.mockReturnValue({ tokens: null, loginAsync });
});
afterEach(() => {
vi.restoreAllMocks();
});
it('logs rejected silent authorization without an unhandled promise', async () => {
const error = new Error('invalid_target');
const log = vi.spyOn(console, 'error').mockImplementation(() => undefined);
getParseQueryStringFromLocation.mockReturnValue({});
loginAsync.mockRejectedValue(error);
render();
await waitFor(() => expect(log).toHaveBeenCalledWith('Silent authorization failed:', error));
});
it.each([{}, { state: 'state' }, { state: 'state', scope: 'openid' }])(
'passes null extras when the query contains only reserved parameters: %s',
query => {
getParseQueryStringFromLocation.mockReturnValue(query);
render();
expect(getOrThrow).toHaveBeenCalledWith('custom');
expect(loginAsync).toHaveBeenCalledExactlyOnceWith(null, null, true, query.scope);
},
);
it('forwards non-reserved parameters without changing the query data', () => {
const query = Object.freeze({
state: 'state',
scope: 'openid profile',
prompt: 'none',
login_hint: 'example',
});
getParseQueryStringFromLocation.mockReturnValue(query);
render();
expect(loginAsync).toHaveBeenCalledExactlyOnceWith(
null,
{ prompt: 'none', login_hint: 'example' },
true,
'openid profile',
);
});
it('does not start login when already authenticated', () => {
getParseQueryStringFromLocation.mockReturnValue({});
getOrThrow.mockReturnValue({ tokens: {}, loginAsync });
render();
expect(loginAsync).not.toHaveBeenCalled();
});
it('starts an explicit silent authorization even when worker tokens were restored', () => {
getParseQueryStringFromLocation.mockReturnValue({ prompt: 'none' });
getOrThrow.mockReturnValue({ tokens: {}, loginAsync });
render();
expect(loginAsync).toHaveBeenCalledExactlyOnceWith(null, { prompt: 'none' }, true, undefined);
});
it('only starts silent login on the initial mount', () => {
getParseQueryStringFromLocation.mockReturnValue({ prompt: 'none' });
const { rerender } = render();
rerender();
expect(loginAsync).toHaveBeenCalledOnce();
});
});