gpt4 book ai didi

javascript - 如何在 jest/enzyme 中测试包含 useIsFocused() 导航钩子(Hook)的 react-native 文件?

转载 作者:行者123 更新时间:2023-12-03 07:08:09 35 4
gpt4 key购买 nike

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

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])
在上面的代码中,如果 bool 值 isFocused 为 true,则动画可以工作,如果为 false(屏幕未聚焦),则动画组件会重置。
我也在使用 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()钩子(Hook)失败,因为组件没有包裹在 <NavigationContainer> 中.
尝试模拟@react-navigation/native通过添加 jest.mock('@react-navigation/native');import 之后测试文件中的语句。还要确保您已遵循 https://reactnavigation.org/docs/testing/ 上的指南。 .

关于javascript - 如何在 jest/enzyme 中测试包含 useIsFocused() 导航钩子(Hook)的 react-native 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62508993/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com