mattermost-mobile-upstream/app/products/calls/hooks.test.ts
Elias Nahum b6fc85385e
Migrate from RNN to Expo router (#9402)
* Expo-Router partial migration

* Full migration to ExpoRouter

* i18n

* add tests

* Merge branch 'main' into expo-router

* align package-lock.json

* i18n

* feedback review

* feedback review

* android 16kb patch

* Refactored emoji picker keyboard using a state machine

* set android launch_screen in drawables instead of layout

* no conditional hooks

* remove duplicate call in test

* address feedback

* fix tests and address more feedback

* small corrections

* small corrections

* small corrections

* fix draft test

* fix draft test 2

* remove navigateToScreen in draff test

* fix nit in draft test

* remove doc file

* Feedback review

* fix snapshots

* improve test coverage

* fix i18n

* Upgrade t o RN 0.83, other dependencies and new architecture (#9737)

* library hardware-keyboard android new arch support fix

* library rnshare android new arch support fix

* library rnutils android new arch support fix

* library secure-pdf-viewer add new arch support

* Enable new arch on iOS and Android

* update emm and network client with new-arch

* update intune to use new-arch

* performance improvements

* fix tests

* fixes post input on new-arch

* fix android emoji picker

* remove doc

* run tests in parallel

* upgrade to React Native 0.83.9, Expo 55, React 19, and New Architecture

Bumps core dependencies to their latest versions:
- React Native 0.77.3 → 0.83.9 (New Architecture enabled)
- React 18.3.1 → 19.2.5
- Expo SDK 52 → 55
- TypeScript 5.8.3 → 6.0.3
- Node.js 22.16.0 → 24.15.0
- react-native-reanimated 3.17.3 → 4.3.0
- Various other dependency upgrades

Migrates iOS AppDelegate from Objective-C to Swift, updates Android
build tooling and Gradle wrapper, refreshes all patches and font
assets, and adapts app code, tests, and CI workflows throughout for
API changes introduced by these upgrades.

* remove unecessary dismissKeyboard in notifications

* feedback review

* update intune to use new-arch

* update @mattermost deps

* missing i18n string

* additional fixes

* update fastlane
2026-05-13 17:44:55 +08:00

281 lines
9.2 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {act, renderHook, waitFor} from '@testing-library/react-native';
import {Alert, AppState} from 'react-native';
import Permissions from 'react-native-permissions';
import {initializeVoiceTrack} from '@calls/actions/calls';
import {
getCurrentCall,
getCallsConfig,
setMicPermissionsGranted,
useCallsState,
useChannelsWithCalls,
useCurrentCall,
useGlobalCallsState,
useIncomingCalls,
} from '@calls/state';
import {Preferences, Screens} from '@constants';
import {
CURRENT_CALL_BAR_HEIGHT,
JOIN_CALL_BAR_HEIGHT,
} from '@constants/view';
import {getDefaultThemeByAppearance, useTheme} from '@context/theme';
import DatabaseManager from '@database/manager';
import NetworkManager from '@managers/network_manager';
import {queryAllActiveServers} from '@queries/app/servers';
import {getCurrentUser} from '@queries/servers/user';
import {navigateToScreen} from '@screens/navigation';
import {openUserProfile} from '@utils/navigation';
import {useTryCallsFunction, usePermissionsChecker, useCallsAdjustment, useHostControlsAvailable, useHostMenus} from './hooks';
jest.mock('react-intl', () => ({
useIntl: jest.fn().mockReturnValue({
formatMessage: jest.fn(({defaultMessage}) => defaultMessage),
}),
defineMessage: (message: any) => message,
defineMessages: (messages: any) => messages,
}));
jest.mock('@context/server', () => ({
useServerUrl: jest.fn(() => 'server1'),
}));
jest.mock('@context/theme', () => ({
useTheme: jest.fn(),
getDefaultThemeByAppearance: jest.fn(),
}));
jest.mocked(useTheme).mockReturnValue(Preferences.THEMES.denim);
jest.mocked(getDefaultThemeByAppearance).mockReturnValue(Preferences.THEMES.denim);
jest.mock('@calls/actions/calls', () => ({
initializeVoiceTrack: jest.fn(),
}));
jest.mock('@calls/state', () => ({
getCurrentCall: jest.fn(),
getCallsConfig: jest.fn(),
setMicPermissionsGranted: jest.fn(),
useCallsState: jest.fn(),
useChannelsWithCalls: jest.fn(),
useCurrentCall: jest.fn(),
useGlobalCallsState: jest.fn(),
useIncomingCalls: jest.fn(),
}));
jest.mock('@managers/network_manager', () => ({
getClient: jest.fn(),
}));
jest.mock('@queries/app/servers', () => ({
queryAllActiveServers: jest.fn(),
}));
jest.mock('@queries/servers/user', () => ({
getCurrentUser: jest.fn(),
}));
jest.mock('@screens/navigation', () => ({
navigateToScreen: jest.fn(),
}));
jest.mock('@utils/navigation');
describe('Calls Hooks', () => {
beforeAll(async () => {
await DatabaseManager.init(['server1']);
});
beforeEach(() => {
jest.clearAllMocks();
});
describe('useTryCallsFunction', () => {
const mockFn = jest.fn();
const mockClient = {
getEnabled: jest.fn(),
};
beforeEach(() => {
(NetworkManager.getClient as jest.Mock).mockReturnValue(mockClient);
});
it('executes function when calls enabled', async () => {
mockClient.getEnabled.mockResolvedValue(true);
const {result} = renderHook(() => useTryCallsFunction(mockFn));
const [tryFn] = result.current;
await act(async () => {
await tryFn();
});
expect(mockFn).toHaveBeenCalled();
});
it('shows alert when calls not enabled', async () => {
mockClient.getEnabled.mockResolvedValue(false);
const mockAlert = jest.spyOn(Alert, 'alert');
const {result} = renderHook(() => useTryCallsFunction(mockFn));
const [tryFn] = result.current;
await act(async () => {
await tryFn();
});
expect(mockFn).not.toHaveBeenCalled();
expect(mockAlert).toHaveBeenCalled();
});
});
describe('usePermissionsChecker', () => {
beforeEach(() => {
jest.spyOn(AppState, 'addEventListener');
});
it('checks permissions when not granted', async () => {
const mockCheck = jest.spyOn(Permissions, 'check').mockResolvedValue(Permissions.RESULTS.GRANTED);
const {result} = renderHook(() => usePermissionsChecker(false));
expect(result.current).toBe(false);
// Simulate app becoming active
await act(async () => {
AppState.currentState = 'active';
const callback = (AppState.addEventListener as jest.Mock).mock.calls[0][1];
await callback('active');
});
expect(mockCheck).toHaveBeenCalled();
expect(initializeVoiceTrack).toHaveBeenCalled();
expect(setMicPermissionsGranted).toHaveBeenCalledWith(true);
expect(result.current).toBe(true);
});
it('skips check when already granted', () => {
const mockCheck = jest.spyOn(Permissions, 'check');
renderHook(() => usePermissionsChecker(true));
expect(mockCheck).not.toHaveBeenCalled();
});
});
describe('useCallsAdjustment', () => {
beforeEach(() => {
(useIncomingCalls as jest.Mock).mockReturnValue({incomingCalls: []});
(useChannelsWithCalls as jest.Mock).mockReturnValue({});
(useCallsState as jest.Mock).mockReturnValue({calls: {}, myUserId: 'user1'});
(useGlobalCallsState as jest.Mock).mockReturnValue({micPermissionsGranted: true});
(useCurrentCall as jest.Mock).mockReturnValue(null);
(queryAllActiveServers as jest.Mock).mockReturnValue({
fetch: () => Promise.resolve([{id: 'server1'}]),
});
});
it('calculates adjustment with no calls', () => {
const {result} = renderHook(() => useCallsAdjustment('server1', 'channel1'));
expect(result.current).toBe(0);
});
it('includes current call bar height', () => {
(useCurrentCall as jest.Mock).mockReturnValue({id: 'call1', channelId: 'channel1'});
const {result} = renderHook(() => useCallsAdjustment('server1', 'channel1'));
expect(result.current).toBe(CURRENT_CALL_BAR_HEIGHT + 8);
});
it('includes join call banner height', () => {
(useChannelsWithCalls as jest.Mock).mockReturnValue({channel1: true});
const {result} = renderHook(() => useCallsAdjustment('server1', 'channel1'));
expect(result.current).toBe(JOIN_CALL_BAR_HEIGHT + 8);
});
});
describe('useHostControlsAvailable', () => {
beforeEach(() => {
(getCallsConfig as jest.Mock).mockReturnValue({
HostControlsAllowed: true,
});
(getCurrentUser as jest.Mock).mockResolvedValue({
roles: 'system_user',
});
});
it('returns true for host', async () => {
(getCurrentCall as jest.Mock).mockReturnValueOnce({
serverUrl: 'server1',
myUserId: 'user1',
hostId: 'user1',
});
const {result} = renderHook(() => useHostControlsAvailable());
expect(result.current).toBe(true);
});
it('returns true for admin', async () => {
(getCurrentCall as jest.Mock).mockReturnValueOnce({
serverUrl: 'server1',
myUserId: 'user1',
hostId: 'host1',
});
(getCurrentUser as jest.Mock).mockResolvedValueOnce({
roles: 'system_admin',
});
const {result} = renderHook(() => useHostControlsAvailable());
await waitFor(() => expect(result.current).toBe(true));
});
});
describe('useHostMenus', () => {
const mockSession = {
userId: 'user1',
sessionId: 'session1',
muted: false,
raisedHand: 0,
};
beforeEach(() => {
(useCurrentCall as jest.Mock).mockReturnValue({
myUserId: 'user1',
hostId: 'host1',
});
(getCallsConfig as jest.Mock).mockReturnValue({
HostControlsAllowed: true,
});
});
it('opens host controls when admin', async () => {
(getCurrentUser as jest.Mock).mockResolvedValueOnce({
roles: 'system_admin',
});
const {result} = renderHook(() => useHostMenus());
await act(async () => {
await result.current.onPress(mockSession)();
});
expect(navigateToScreen).toHaveBeenCalledWith(Screens.CALL_HOST_CONTROLS, {sessionId: 'session1'});
});
it('opens host controls when host and clicking another profile', async () => {
(useCurrentCall as jest.Mock).mockReturnValue({
myUserId: 'user1',
hostId: 'user1',
});
const {result} = renderHook(() => useHostMenus());
await act(async () => {
await result.current.onPress(mockSession)();
});
expect(openUserProfile).toHaveBeenCalledWith(
expect.objectContaining({
userId: mockSession.userId,
}),
);
});
});
});