如何使用 jest 和 React 测试库来模拟 @react-navigation/native

问题描述 投票:0回答:1

我有标头组件,用 React Native 编写。 当

onPress
被触发时,它应该执行
goBack
函数,但它只记录 'onPressCalled' 并且不输入 if 语句。看起来模拟没有正确应用,并且测试没有使用模拟版本的导航,因此失败了。

import {
    ArrowIcon,
    HeaderComponent,
    IconWrapper,
    PageTitle,
    PlaceholderView,
} from './Header.style';
import { Poppins_500Medium, useFonts } from '@expo-google-fonts/poppins';
import { useNavigation } from '@react-navigation/native';

const Header = () => {
    const navigation = useNavigation();
    const [loaded, error] = useFonts({
        Poppins_500Medium,
    });

    if (error || !loaded) {
        return <></>;
    }

    return (
        <HeaderComponent>
            <IconWrapper
                onPress={() => {
                    console.log('onPressCalled');
                    if (navigation.canGoBack()) {
                        console.log('usao1');
                        navigation.goBack();
                    }
                }}
            >
                <ArrowIcon
                    name='left'
                    color='#fff'
                    size={24}
                />
            </IconWrapper>
            <PageTitle>Create account</PageTitle>
            <PlaceholderView />
        </HeaderComponent>
    );
};

export default Header;

以及它的测试套件:

import { fireEvent, render, waitFor } from '../../../test-utils';
import Header from './Header.component';

describe('Header', () => {
    // Clicking the back button navigates to the previous screen
    it.only('should navigate to previous screen when back button is clicked', async () => {
        // Mock the necessary dependencies
        const navigation = {
            canGoBack: jest.fn().mockReturnValue(true),
            goBack: jest.fn(),
        };

        // Mock the required imports
        jest.doMock('@react-navigation/native', () => ({
            useNavigation: jest.fn().mockReturnValue(navigation),
        }));
        jest.doMock('@expo-google-fonts/poppins', () => ({
            Poppins_500Medium: 'Poppins_500Medium',
            useFonts: jest.fn().mockReturnValue([true, null]),
        }));

        // Render the component
        const { findByTestId } = render(<Header />);

        const iconWrapper = await findByTestId('IconWrapper');

        // Simulate click on the back button
        fireEvent.press(iconWrapper);

        // Assert that the navigation.goBack function is called
        await waitFor(() => {
            expect(navigation.goBack).toHaveBeenCalled();
        });
    });
})
reactjs react-native jestjs react-testing-library react-native-navigation
1个回答
0
投票

我认为这应该有效:

// Mock the useNavigation hook to return a navigation object
const mockNavigation = jest.fn();
const mockGoBack = jest.fn();
jest.mock('@react-navigation/native', () => {
  const actualNavigation = jest.requireActual('@react-navigation/native');
  return {
    ...actualNavigation,
    useNavigation: () => ({
      navigate: mockNavigation,
      goBack: mockGoBack,
    }),
  };
});

您模拟 useNavigation 以返回您定义的模拟函数。然后您可以检查他们是否被调用。您可以将其放入测试文件或 jest.setup 中,以便在全局范围内模拟它们。

© www.soinside.com 2019 - 2024. All rights reserved.