如何测试点击按钮时目标函数是否执行?React Native测试求助
要验证点击卡片时navigateToProduct函数是否正确触发navigate调用,你可以通过mockuseNavigation并断言其方法的调用情况来实现,具体步骤如下:
1. 调整测试用例代码
修改你的测试文件,为useNavigation创建mock函数,并在点击后验证调用参数:
import {fireEvent, render, screen} from '@testing-library/react-native'; import ProductItem from '..'; import { useNavigation } from '@react-navigation/native'; // Mock useNavigation(如果已有全局mock可跳过此步) jest.mock('@react-navigation/native', () => ({ useNavigation: jest.fn(), })); describe('<ProductItem/>', () => { const product = { title: 'title-test', id: 1, rating: 4.5, category: 'category-test', price: 499, thumbnail: 'thumbnail-test', description: 'description-test', stock: 1, brand: 'brand-test', images: ['image1-test', 'image2-test'], }; it('Should render correctly product item component', () => { render(<ProductItem {...product} />); const title = screen.getByText(product.title); expect(title).toBeTruthy(); }); it('Should trigger navigate with correct params when card is pressed', () => { // 创建mock的navigate函数 const mockNavigate = jest.fn(); // 让useNavigation返回包含该mock的对象 (useNavigation as jest.Mock).mockReturnValue({ navigate: mockNavigate }); render(<ProductItem {...product} />); // 触发点击事件 const productCard = screen.getByTestId('button-nav'); fireEvent.press(productCard); // 断言navigate被正确调用 expect(mockNavigate).toHaveBeenCalledTimes(1); expect(mockNavigate).toHaveBeenCalledWith('Product', { id: product.id, title: product.title }); }); });
2. 针对全局mock的适配
如果你已经在项目中配置了全局的useNavigation mock(比如在__mocks__/@react-navigation/native.js中),只需在测试用例中覆盖其返回值即可:
// 全局mock文件 __mocks__/@react-navigation/native.js export const useNavigation = jest.fn(() => ({ navigate: jest.fn(), })); // 测试用例中 it('Should trigger navigate with correct params when card is pressed', () => { const mockNavigate = jest.fn(); (useNavigation as jest.Mock).mockReturnValue({ navigate: mockNavigate }); // 后续渲染、点击、断言步骤同上 });
原理说明
- 通过mock
useNavigation,我们可以完全控制组件获取到的导航对象,避免依赖真实的导航环境。 - 创建的
mockNavigate函数会记录所有调用行为,包括调用次数和传入的参数,以此验证navigateToProduct函数是否按预期执行了导航逻辑。
内容的提问来源于stack exchange,提问作者LayTexas
相关产品推荐
相关产品推荐

