如何在包含useIsFocussed()导航钩子的jest/enzyme中测试反应原生文件?



我在 react-native 中创建了一个容器,并在屏幕上添加了动画。为了检查屏幕是否聚焦,我正在使用来自@react导航/本机库中的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])

在上面的代码中,如果布尔值为真,则动画工作,如果其为假(屏幕未聚焦(,则动画组件将重置。 我也在使用笑话/酶测试这个屏幕。以下是屏幕测试的代码

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()钩失败,因为组件未包装在<NavigationContainer>中。

尝试通过在测试文件中的import语句后添加jest.mock('@react-navigation/native');来模拟@react-navigation/native。还要确保您遵循了 https://reactnavigation.org/docs/testing/中的准则。

特别是对于useIsFocused(),这就是我能够运行测试的方式:

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

最新更新