Sud*_*han 5 javascript jestjs react-native enzyme react-navigation
我在 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])
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,如果布尔值 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')
})
})
Run Code Online (Sandbox Code Playgroud)
但是在运行测试时,我面临这个问题
Couldn't find a navigation object. Is your component inside a screen in a navigator?
Run Code Online (Sandbox Code Playgroud)
谁能告诉我如何解决这个错误?
特别是对于useIsFocused(),这就是我能够运行测试的方式:
jest.mock('@react-navigation/native', () => ({
useIsFocused: jest.fn(),
}));
Run Code Online (Sandbox Code Playgroud)
调用useIsFocused()钩子失败,因为组件没有包装在<NavigationContainer>.
尝试@react-navigation/native通过在测试文件中jest.mock('@react-navigation/native');的import语句之后添加来模拟。还要确保您已遵循https://reactnavigation.org/docs/testing/ 上的指南。
| 归档时间: |
|
| 查看次数: |
1922 次 |
| 最近记录: |