Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
},
"devDependencies": {
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.15.3",
"@types/react": "^19.1.5",
"@vitest/browser": "^3.1.3",
Expand All @@ -62,8 +63,8 @@
"react": ">=16.8.0"
},
"dependencies": {
"@asgardeo/i18n": "workspace:^",
"@asgardeo/browser": "workspace:^",
"@asgardeo/i18n": "workspace:^",
"@emotion/css": "^11.13.5",
"@floating-ui/react": "^0.27.12",
"@types/react-dom": "^19.1.5",
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
92 changes: 92 additions & 0 deletions packages/react/src/__test__/useBranding.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import {renderHook} from '@testing-library/react';
import useBranding from '../hooks/useBranding';
import {vi, describe, it, expect, afterEach} from 'vitest';

// Mock the context and make default export a vi.fn()
vi.mock('../contexts/Branding/useBrandingContext', () => {
return {default: vi.fn()};
});

// Import the mocked function
import useBrandingContext from '../contexts/Branding/useBrandingContext';

describe('useBranding hook', () => {
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});

afterEach(() => {
vi.resetAllMocks();
});

it('returns values from context when available', () => {
const mockReturn = {
brandingPreference: {name: 'TestBrand'},
theme: {colors: {primary: {main: '#000'}}},
activeTheme: 'light',
isLoading: false,
error: null,
fetchBranding: vi.fn(),
refetch: vi.fn(),
};

(useBrandingContext as unknown as ReturnType<typeof vi.fn>).mockReturnValue(mockReturn);

const {result} = renderHook(() => useBranding());

expect(result.current.brandingPreference).toEqual(mockReturn.brandingPreference);
expect(result.current.theme).toEqual(mockReturn.theme);
expect(result.current.activeTheme).toBe('light');
expect(result.current.isLoading).toBe(false);
expect(result.current.error).toBeNull();
expect(typeof result.current.fetchBranding).toBe('function');
expect(typeof result.current.refetch).toBe('function');
});

it('returns default values when context is missing', async () => {
(useBrandingContext as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => {
throw new Error('Provider missing');
});

const {result} = renderHook(() => useBranding());

expect(result.current.brandingPreference).toBeNull();
expect(result.current.theme).toBeNull();
expect(result.current.activeTheme).toBeNull();
expect(result.current.isLoading).toBe(false);
expect(result.current.error).toBeInstanceOf(Error);

await expect(result.current.fetchBranding()).resolves.toBeUndefined();
await expect(result.current.refetch()).resolves.toBeUndefined();

expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining('useBranding: BrandingProvider not available'));
});

it('accepts a config object without breaking', () => {
(useBrandingContext as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => {
throw new Error('Provider missing');
});

const {result} = renderHook(() => useBranding({locale: 'en', autoFetch: true}));

expect(result.current.brandingPreference).toBeNull();
expect(result.current.theme).toBeNull();
expect(result.current.activeTheme).toBeNull();
});
});
78 changes: 78 additions & 0 deletions packages/react/src/__test__/useBrowserUrl.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import useBrowserUrl from '../hooks/useBrowserUrl';
import {hasAuthParamsInUrl} from '@asgardeo/browser';
import {vi, describe, it, expect, beforeEach} from 'vitest';

// Mock the module
vi.mock('@asgardeo/browser', () => ({
hasAuthParamsInUrl: vi.fn(),
}));

describe('useBrowserUrl hook', () => {
const {hasAuthParams} = useBrowserUrl();

beforeEach(() => {
vi.clearAllMocks();
});

it('returns true if hasAuthParamsInUrl returns true and URL matches afterSignInUrl', () => {
(hasAuthParamsInUrl as unknown as ReturnType<typeof vi.fn>).mockReturnValue(true);
const url = new URL('https://example.com/callback');
const afterSignInUrl = 'https://example.com/callback';
expect(hasAuthParams(url, afterSignInUrl)).toBe(true);
});

it('returns false if hasAuthParamsInUrl returns false and no error param exists', () => {
(hasAuthParamsInUrl as unknown as ReturnType<typeof vi.fn>).mockReturnValue(false);
const url = new URL('https://example.com/callback');
const afterSignInUrl = 'https://example.com/other';
expect(hasAuthParams(url, afterSignInUrl)).toBe(false);
});

it('returns true if URL contains error param', () => {
(hasAuthParamsInUrl as unknown as ReturnType<typeof vi.fn>).mockReturnValue(false);
const url = new URL('https://example.com/callback?error=access_denied');
const afterSignInUrl = 'https://example.com/other';
expect(hasAuthParams(url, afterSignInUrl)).toBe(true);
});

it('returns false if URL does not match afterSignInUrl and no error param and hasAuthParamsInUrl false', () => {
(hasAuthParamsInUrl as unknown as ReturnType<typeof vi.fn>).mockReturnValue(false);
const url = new URL('https://example.com/callback');
const afterSignInUrl = 'https://example.com/other';
expect(hasAuthParams(url, afterSignInUrl)).toBe(false);
});

// Edge case: trailing slash mismatch
it('normalizes URLs with trailing slashes', () => {
(hasAuthParamsInUrl as unknown as ReturnType<typeof vi.fn>).mockReturnValue(true);
const url = new URL('https://example.com/callback/');
const afterSignInUrl = 'https://example.com/callback';
expect(hasAuthParams(url, afterSignInUrl)).toBe(false); // still false due to exact match
});

// Edge case: relative afterSignInUrl
it('handles relative afterSignInUrl', () => {
(hasAuthParamsInUrl as unknown as ReturnType<typeof vi.fn>).mockReturnValue(true);
const url = new URL('https://example.com/callback');
const afterSignInUrl = '/callback';
expect(hasAuthParams(url, afterSignInUrl)).toBe(false); // relative URL fails exact match
});
});
185 changes: 185 additions & 0 deletions packages/react/src/__test__/useForm.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/**
* Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import {renderHook, act} from '@testing-library/react';
import {useForm, UseFormConfig} from '../hooks/useForm';
import {vi, describe, it, expect} from 'vitest';

interface LoginForm extends Record<string, string> {
username: string;
password: string;
email?: string;
}

describe('useForm hook - full coverage', () => {
const initialValues: LoginForm = {username: '', password: '', email: ''};
const fields = [
{name: 'username', required: true},
{name: 'password', required: true},
{name: 'email', required: false, validator: (value: string) => (value.includes('@') ? null : 'Invalid email')},
];

const globalValidator = (values: LoginForm) => {
const errors: Record<string, string> = {};
if (values.password && values.password.length < 6) {
errors['password'] = 'Password too short';
}
return errors;
};

const config: UseFormConfig<LoginForm> = {initialValues, fields, validator: globalValidator};

it('initial state', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
expect(result.current.values).toEqual(initialValues);
expect(result.current.errors).toEqual({});
expect(result.current.touched).toEqual({});
expect(result.current.isValid).toBe(true);
expect(result.current.isSubmitted).toBe(false);
});

it('setValue and validate on change', () => {
const {result} = renderHook(() => useForm<LoginForm>({...config, validateOnChange: true}));

act(() => result.current.setValue('username', 'Alice'));
expect(result.current.values.username).toBe('Alice');

act(() => result.current.setValue('email', 'wrong-email'));
expect(result.current.errors['email']).toBe('Invalid email');

act(() => result.current.setValue('email', 'alice@example.com'));
expect(result.current.errors['email']).toBeUndefined();
});

it('bulk setValues', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));

act(() => result.current.setValues({username: 'Bob', password: '123456'}));
expect(result.current.values.username).toBe('Bob');
expect(result.current.values.password).toBe('123456');
});

it('setTouched and validate on blur', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));

act(() => result.current.setTouched('username'));
expect(result.current.touched['username']).toBe(true);
expect(result.current.errors['username']).toBe('This field is required');
});

it('bulk setTouchedFields', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
act(() => result.current.setTouchedFields({username: true, password: true}));
expect(result.current.touched['username']).toBe(true);
expect(result.current.touched['password']).toBe(true);
});

it('touchAllFields triggers validation', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
act(() => result.current.touchAllFields());
expect(result.current.touched['username']).toBe(true);
expect(result.current.touched['password']).toBe(true);
expect(result.current.errors['username']).toBe('This field is required');
});

it('setErrors and clearErrors', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
act(() => result.current.setErrors({username: 'Custom error', password: 'Another error'}));
expect(result.current.errors['username']).toBe('Custom error');
expect(result.current.errors['password']).toBe('Another error');

act(() => result.current.clearErrors());
expect(result.current.errors).toEqual({});
});

it('validateField returns correct errors', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
act(() => result.current.setValue('email', 'invalid'));
expect(result.current.validateField('email')).toBe('Invalid email');
expect(result.current.validateField('username')).toBe('This field is required');
});

it('validateForm returns correct ValidationResult', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
act(() => result.current.setValue('password', '123'));
const validation = result.current.validateForm();
expect(validation.isValid).toBe(false);
expect(validation.errors['password']).toBe('Password too short');
});

it('handleSubmit prevents submission if invalid', async () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
const onSubmit = vi.fn();

await act(async () => {
await result.current.handleSubmit(onSubmit)({preventDefault: vi.fn()} as any);
});

expect(onSubmit).not.toHaveBeenCalled();
expect(result.current.isSubmitted).toBe(true);
});

it('handleSubmit calls onSubmit if valid', async () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
const onSubmit = vi.fn();

act(() => {
result.current.setValues({username: 'Alice', password: '123456', email: 'alice@example.com'});
});

await act(async () => {
await result.current.handleSubmit(onSubmit)();
});

expect(onSubmit).toHaveBeenCalledWith({username: 'Alice', password: '123456', email: 'alice@example.com'});
});

it('reset restores initial state', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
act(() => {
result.current.setValue('username', 'Changed');
result.current.setTouched('username');
result.current.setError('username', 'Error');
result.current.reset();
});

expect(result.current.values).toEqual(initialValues);
expect(result.current.touched).toEqual({});
expect(result.current.errors).toEqual({});
expect(result.current.isSubmitted).toBe(false);
});

it('getFieldProps works correctly', () => {
const {result} = renderHook(() => useForm<LoginForm>(config));
const props = result.current.getFieldProps('username');

expect(props.name).toBe('username');
expect(props.required).toBe(true);
expect(props.value).toBe('');
expect(props.touched).toBe(false);
expect(props.error).toBeUndefined();
expect(typeof props.onBlur).toBe('function');
expect(typeof props.onChange).toBe('function');

act(() => props.onChange('NewValue'));
expect(result.current.values.username).toBe('NewValue');

act(() => props.onBlur());
expect(result.current.touched['username']).toBe(true);
});
});
Loading