Files
api/web/__test__/components/SsoButton.test.ts
Eli Bosley 3b00fec5fd chore: Remove legacy store modules and add new API key and reporting services (#1536)
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added developer CLI tools for toggling GraphQL sandbox and modal
testing utilities.
* Introduced a "Show Activation Modal" developer component for UI
testing.
  * Added system initial setup detection and related GraphQL queries.
* Enhanced login and welcome pages with dynamic server info and initial
setup state.
  * Improved SSO button with internationalization and error handling.
* Added internal CLI admin API key management service and internal
GraphQL client service.
* Introduced comprehensive API report generation service for system and
service status.
* Added CLI commands and GraphQL mutations/queries for plugin and SSO
user management.
* Added new modal target components and improved teleport target
detection.

* **Enhancements**
* Refined modal dialog targeting and teleportation for flexible UI
placement.
* Updated modal components and stores for improved activation/welcome
modal control.
  * Improved plugin and SSO user management via CLI through GraphQL API.
* Refactored partner logo components to use props instead of store
dependencies.
  * Enhanced styling and accessibility for buttons and modals.
* Streamlined Tailwind CSS integration with shared styles and updated
theme variables.
* Improved GraphQL module configuration to avoid directive conflicts in
tests.
  * Adjusted Vite config for better dependency handling in test mode.
  * Improved error handling and logging in CLI commands and services.
* Reordered imports and refined component class bindings for UI
consistency.

* **Bug Fixes**
* Resolved issues with duplicate script tags and component registration
in the web UI.
* Fixed modal close button visibility and activation modal state
handling.
* Added error handling and logging improvements across CLI commands and
services.
  * Fixed newline issues in last-download-time fixture files.

* **Chores**
* Added and updated numerous tests for CLI commands, services, and UI
components.
* Updated translation files and localization resources for new UI
messages.
* Adjusted environment, configuration, and dependency files for improved
development and test workflows.
  * Cleaned up unused imports and mocks in tests.
  * Reorganized exports and barrel files in shared and UI modules.
  * Added integration and dependency resolution tests for core modules.

* **Removals & Refactoring**
* Removed legacy Redux state management, configuration, and UPnP logic
from the backend.
* Eliminated deprecated GraphQL subscriptions and client code related to
registration and mothership.
* Removed direct store manipulation and replaced with service-based
approaches in CLI commands.
  * Deleted unused or redundant test files and configuration listeners.
* Refactored SSO user service to consolidate add/remove operations into
a single update method.
* Simplified API key services with new methods for automatic key
management.
* Replaced direct plugin and SSO user service calls with GraphQL client
interactions in CLI commands.
* Removed complex theme fallback and dark mode CSS rules, replacing with
streamlined static theme variables.
* Cleaned up Tailwind CSS configuration and removed deprecated local
styles.
* Removed multiple internal utility files and replaced with simplified
or centralized implementations.
* Removed deprecated local configuration and synchronization files and
listeners.
  * Removed UPnP helper functions and job management classes.
* Refactored server resolver to dynamically construct local server data
internally.
* Removed CORS handler and replaced with simplified or externalized
logic.
* Removed store synchronization and registration event pubsub handling.
* Removed GraphQL client creation utilities for internal API
communication.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2025-07-25 15:07:37 -04:00

331 lines
9.8 KiB
TypeScript

/**
* SsoButton Component Test Coverage
*/
import { useQuery } from '@vue/apollo-composable';
import { flushPromises, mount } from '@vue/test-utils';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Mock, MockInstance } from 'vitest';
import SsoButton from '~/components/SsoButton.ce.vue';
const BrandButtonStub = {
template: '<button><slot /></button>',
props: ['disabled', 'variant', 'class'],
};
// Mock the GraphQL composable
vi.mock('@vue/apollo-composable', () => ({
useQuery: vi.fn(),
}));
// Mock vue-i18n
const t = (key: string) => key;
vi.mock('vue-i18n', () => ({
useI18n: () => ({ t }),
}));
vi.mock('~/helpers/urls', () => ({
ACCOUNT: 'http://mock-account-url.net',
}));
vi.mock('~/store/account.fragment', () => ({
SSO_ENABLED: 'SSO_ENABLED_QUERY',
}));
// Mock window APIs
vi.stubGlobal('fetch', vi.fn());
vi.stubGlobal('sessionStorage', {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
clear: vi.fn(),
});
const mockCrypto = {
getRandomValues: vi.fn((array: Uint8Array) => {
for (let i = 0; i < array.length; i++) {
array[i] = Math.floor(Math.random() * 256);
}
return array;
}),
};
vi.stubGlobal('crypto', mockCrypto);
const mockLocation = {
search: '',
origin: 'http://mock-origin.com',
pathname: '/login',
href: '',
};
vi.stubGlobal('location', mockLocation);
vi.stubGlobal('URLSearchParams', URLSearchParams);
vi.stubGlobal('URL', URL);
const mockHistory = {
replaceState: vi.fn(),
};
vi.stubGlobal('history', mockHistory);
// Mock DOM interactions
const mockForm = {
requestSubmit: vi.fn(),
style: { display: 'block' },
};
const mockPasswordField = { value: '' };
const mockUsernameField = { value: '' };
describe('SsoButton.ce.vue', () => {
let querySelectorSpy: MockInstance;
let mockUseQuery: Mock;
beforeEach(async () => {
vi.restoreAllMocks();
mockUseQuery = useQuery as Mock;
(sessionStorage.getItem as Mock).mockReturnValue(null);
(sessionStorage.setItem as Mock).mockClear();
mockForm.requestSubmit.mockClear();
mockPasswordField.value = '';
mockUsernameField.value = '';
mockForm.style.display = 'block';
mockLocation.search = '';
mockLocation.href = '';
(fetch as Mock).mockClear();
mockUseQuery.mockClear();
// Spy on document.querySelector and provide mock implementation
querySelectorSpy = vi.spyOn(document, 'querySelector');
querySelectorSpy.mockImplementation((selector: string) => {
if (selector === 'form[action="/login"]') return mockForm as unknown as HTMLFormElement;
if (selector === 'input[name=password]') return mockPasswordField as unknown as HTMLInputElement;
if (selector === 'input[name=username]') return mockUsernameField as unknown as HTMLInputElement;
return null;
});
Object.defineProperty(document, 'title', {
value: 'Mock Title',
writable: true,
});
});
afterEach(() => {
vi.restoreAllMocks();
});
it('renders the button when SSO is enabled via GraphQL', () => {
mockUseQuery.mockReturnValue({
result: { value: { isSSOEnabled: true } },
});
const wrapper = mount(SsoButton, {
global: {
stubs: { BrandButton: BrandButtonStub },
},
});
expect(wrapper.findComponent(BrandButtonStub).exists()).toBe(true);
expect(wrapper.text()).toContain('or');
expect(wrapper.text()).toContain('Log In With Unraid.net');
});
it('does not render the button when SSO is disabled via GraphQL', () => {
mockUseQuery.mockReturnValue({
result: { value: { isSSOEnabled: false } },
});
const wrapper = mount(SsoButton, {
global: {
stubs: { BrandButton: BrandButtonStub },
},
});
expect(wrapper.findComponent(BrandButtonStub).exists()).toBe(false);
expect(wrapper.text()).not.toContain('or');
});
it('does not render the button when GraphQL result is null/undefined', () => {
mockUseQuery.mockReturnValue({
result: { value: null },
});
const wrapper = mount(SsoButton, {
global: {
stubs: { BrandButton: BrandButtonStub },
},
});
expect(wrapper.findComponent(BrandButtonStub).exists()).toBe(false);
expect(wrapper.text()).not.toContain('or');
});
it('does not render the button when GraphQL result is undefined', () => {
mockUseQuery.mockReturnValue({
result: { value: undefined },
});
const wrapper = mount(SsoButton, {
global: {
stubs: { BrandButton: BrandButtonStub },
},
});
expect(wrapper.findComponent(BrandButtonStub).exists()).toBe(false);
expect(wrapper.text()).not.toContain('or');
});
it('navigates to the external SSO URL on button click', async () => {
mockUseQuery.mockReturnValue({
result: { value: { isSSOEnabled: true } },
});
const wrapper = mount(SsoButton, {
global: {
stubs: { BrandButton: BrandButtonStub },
},
});
const button = wrapper.findComponent(BrandButtonStub);
await button.trigger('click');
expect(sessionStorage.setItem).toHaveBeenCalledTimes(1);
expect(sessionStorage.setItem).toHaveBeenCalledWith('sso_state', expect.any(String));
const generatedState = (sessionStorage.setItem as Mock).mock.calls[0][1];
const expectedUrl = new URL('sso', 'http://mock-account-url.net');
const expectedCallbackUrl = new URL('login', 'http://mock-origin.com');
expectedUrl.searchParams.append('callbackUrl', expectedCallbackUrl.toString());
expectedUrl.searchParams.append('state', generatedState);
expect(mockLocation.href).toBe(expectedUrl.toString());
});
it('handles SSO callback in onMounted hook successfully', async () => {
mockUseQuery.mockReturnValue({
result: { value: { isSSOEnabled: true } },
});
const mockCode = 'mock_auth_code';
const mockState = 'mock_session_state_value';
const mockAccessToken = 'mock_access_token_123';
mockLocation.search = `?code=${mockCode}&state=${mockState}`;
(sessionStorage.getItem as Mock).mockReturnValue(mockState);
(fetch as Mock).mockResolvedValueOnce({
ok: true,
json: async () => ({ access_token: mockAccessToken }),
} as Response);
// Mount the component so that onMounted hook is called
mount(SsoButton, {
global: {
stubs: { BrandButton: BrandButtonStub },
},
});
await flushPromises();
expect(sessionStorage.getItem).toHaveBeenCalledWith('sso_state');
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith(new URL('/api/oauth2/token', 'http://mock-account-url.net'), {
method: 'POST',
body: new URLSearchParams({
code: mockCode,
client_id: 'CONNECT_SERVER_SSO',
grant_type: 'authorization_code',
}),
});
expect(mockForm.style.display).toBe('none');
expect(mockUsernameField.value).toBe('root');
expect(mockPasswordField.value).toBe(mockAccessToken);
expect(mockForm.requestSubmit).toHaveBeenCalledTimes(1);
expect(mockHistory.replaceState).toHaveBeenCalledWith({}, 'Mock Title', '/login');
});
it('handles SSO callback error in onMounted hook', async () => {
mockUseQuery.mockReturnValue({
result: { value: { isSSOEnabled: true } },
});
const mockCode = 'mock_auth_code_error';
const mockState = 'mock_session_state_error';
mockLocation.search = `?code=${mockCode}&state=${mockState}`;
(sessionStorage.getItem as Mock).mockReturnValue(mockState);
const fetchError = new Error('Failed to fetch token');
(fetch as Mock).mockRejectedValueOnce(fetchError);
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const wrapper = mount(SsoButton, {
global: {
stubs: { BrandButton: BrandButtonStub },
},
});
await flushPromises();
expect(sessionStorage.getItem).toHaveBeenCalledWith('sso_state');
expect(fetch).toHaveBeenCalledTimes(1);
expect(consoleErrorSpy).toHaveBeenCalledWith('Error fetching token', fetchError);
const errorElement = wrapper.find('p.text-red-500');
expect(errorElement.exists()).toBe(true);
expect(errorElement.text()).toBe('Error fetching token');
const button = wrapper.findComponent(BrandButtonStub);
expect(button.text()).toBe('Try Again');
expect(mockForm.style.display).toBe('block');
expect(mockForm.requestSubmit).not.toHaveBeenCalled();
consoleErrorSpy.mockRestore();
});
it('handles SSO callback when state does not match', async () => {
mockUseQuery.mockReturnValue({
result: { value: { isSSOEnabled: true } },
});
const mockCode = 'mock_auth_code';
const mockState = 'mock_session_state_value';
const differentState = 'different_state_value';
mockLocation.search = `?code=${mockCode}&state=${mockState}`;
(sessionStorage.getItem as Mock).mockReturnValue(differentState);
const wrapper = mount(SsoButton, {
global: {
stubs: { BrandButton: BrandButtonStub },
},
});
await flushPromises();
// Should not make any fetch calls when state doesn't match
expect(fetch).not.toHaveBeenCalled();
expect(mockForm.requestSubmit).not.toHaveBeenCalled();
expect(wrapper.findComponent(BrandButtonStub).text()).toBe('Log In With Unraid.net');
});
it('handles SSO callback when no code is present', async () => {
mockUseQuery.mockReturnValue({
result: { value: { isSSOEnabled: true } },
});
mockLocation.search = '?state=some_state';
(sessionStorage.getItem as Mock).mockReturnValue('some_state');
const wrapper = mount(SsoButton, {
global: {
stubs: { BrandButton: BrandButtonStub },
},
});
await flushPromises();
// Should not make any fetch calls when no code is present
expect(fetch).not.toHaveBeenCalled();
expect(mockForm.requestSubmit).not.toHaveBeenCalled();
expect(wrapper.findComponent(BrandButtonStub).text()).toBe('Log In With Unraid.net');
});
});