使用useRoute()对导航单元测试组件进行反应



我有一个组件

export function Component() {
const route = useRoute<RouteProp<StackParamList>>();
const amount = route.params.amount
return (<View> <Text>{amount} is now</Text></View>)
}

我的测试很简单,但失败了,我只是在检查文本是否被渲染。

test('should display amount', () => {
const screen = renderWithWrapper(
<Navigation>
<Component />
</Navigation>
) 
expect(screen.queryByText(/is now/))
})

这里的代码失败了const amount = route.params.amount说TypeError:无法读取未定义(.reading params(的属性。

我想我的问题是如何模拟useRoute来接收amount参数??

我做类似事情的方式是使用Spy:


test('should display amount', () => {
const mockUseRoute = jest.spyOn(require('@react-navigation/native'), 'useRoute');
mockUseRoute.mockImplementation(() => ({
params: {
amount: 1000,
},
}));
const screen = renderWithWrapper(
<Navigation>
<Component />
</Navigation>
) 
expect(screen.queryByText(/is now/))
})

最新更新