Jest.js 如何在函数组件react native中调用const函数?

a0zr77ik  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(129)
  1. const goToLoginPage = () => {
  2. navigation.navigate(AppConstants.LOGIN_SCREEN)
  3. });
  4. <TouchableOpacity onPress={goToLogin}>
  5. <Text>OK</Text>
  6. </TouchableOpacity>

如何使用Jest调用此方法?

nhaq1z21

nhaq1z211#

您需要模拟导航,以便能够检查是否调用了它

  1. // Mock the useNavigation hook to return a navigation object
  2. const mockNavigation = jest.fn();
  3. jest.mock('@react-navigation/native', () => {
  4. const actualNavigation = jest.requireActual('@react-navigation/native');
  5. return {
  6. ...actualNavigation,
  7. useNavigation: () => ({
  8. navigate: mockNavigation,
  9. }),
  10. };
  11. });
  12. it('test if callback is being called', () => {
  13. // GIVEN
  14. render(
  15. <NavigationContainer>
  16. <theComponent>
  17. </NavigationContainer>
  18. )
  19. const button = screen.getByText('OK')
  20. //WHEN
  21. fireEvent.press(button)
  22. //THEN
  23. expect(mockNavigation).toHaveBeenCalledWith(AppConstants.LOGIN_SCREEN)
  24. })
展开查看全部

相关问题