繁体   English   中英

如何测试 jest/enzyme 中包含 useIsFocussed() 导航挂钩的 react-native 个文件?

[英]How to test react-native files in jest/enzyme which contain the useIsFocussed() navigation hook?

我在 react-native 中创建了一个容器,并在屏幕上添加了动画。 为了检查屏幕是否聚焦,我使用了 @react-navigation/native 库中的 useIsFocussed 钩子。

const isFocused = useIsFocused()
  useEffect(() => {
    if (isFocused) {
      pulse()
    } else {
      posAnim.setValue({ x: Width, y: 0 })
      fadeModal.setValue(0)
      posModal.setValue({ x: 0, y: (50 / 812) * Height })
    }
  }, [isFocused])

在上面的代码中,如果 boolean isFocused 为真,则 animation 有效,如果为假(屏幕未聚焦),动画组件将重置。 我也在使用 jest/enzyme 测试这个屏幕。 下面是屏幕测试的代码

const createTestProps = () => ({
  navigation: {
    navigate: jest.fn()
  }
})
describe('Screen', () => {
  let wrapper
  let props
  beforeEach(() => {
    props = createTestProps({})
    wrapper = shallow(<Screen {...props} />) // no compile-time error
  })
  it('should match to snapshot', () => {
    expect(wrapper).toMatchSnapshot()
  })
  it('Navigate ', () => {
    wrapper.find(TouchableOpacity).at(0).props().onPress()
    expect(props.navigation.navigate).toHaveBeenCalledWith('Screen2')
  })
})

但是在运行测试时,我遇到了这个问题

 Couldn't find a navigation object. Is your component inside a screen in a navigator?

谁能告诉我如何解决这个错误?

专门针对useIsFocused() ,这就是我能够运行测试的方式:

jest.mock('@react-navigation/native', () => ({
  useIsFocused: jest.fn(),
}));

调用useIsFocused()挂钩失败,因为该组件未包装在<NavigationContainer>中。

尝试 mocking @react-navigation/native通过添加jest.mock('@react-navigation/native'); 在测试文件中的import语句之后。 还要确保您已遵循https://reactnavigation.org/docs/testing/中的指南。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM