我目前正致力于为react-navigation添加jest单元测试,例如: 我的StackNavigator
const Nav = StackNavigator({
Home: {
screen: Home,
},
Second: {
screen: Second,
}
});
export default class App extends Component<{}> {
render() {
return (
<Nav/>
);
}
}
我的主页组件
export default class Home extends Component<{}> {
_goToNextPage = () => {
this.props.navigation.navigate('Second');
}
render() {
return (
<View>
<Text>Home</Text>
<Button
onPress={this._goToNextPage}
title="Go to Second Page"
>Click to next page</Button>
</View>
);
}
}
我的第二部分 export default class Second extends Component&lt; {}&gt; {
render() {
return (
<View>
<Text>Second</Text>
</View>
);
}
}
当我点击GoToNextPage按钮,第二个组件应该正确渲染时,我应该如何编写测试单元测试来测试?“
我没有找到任何有关反应导航的开玩笑的有用信息,任何帮助将非常感谢!!!
非常感谢〜
答案 0 :(得分:0)
我个人喜欢@testing-library/react
,因为他们围绕着从用户角度进行测试的理念。我以为您的测试将如下所示:
it('shows the second component when the next button is clicked', async () => {
// Renders your app
const { getByText, findByText } = render(<App />);
// Clicks your button
fireEvent.click(getByText('Click to next page'));
// Waits for the 'Second' text to be visible, could be async or sync, in this
// case I'm using the async expectation style
await wait(() => expect(getByText('Second')));
});
我将通过简单地呈现第二个组件并根据快照对其进行检查的方式,将按钮的单击和其正确呈现的验证的关注点分离开来进行测试。
// inside your second component test - still using testing-library
it('matches the snapshot', () => {
expect(render(<Second />).container).toMatchSnapshot();
});