当前正在尝试测试单击按钮“ onPress”后是否已被调用,但是我遇到了一些麻烦。在我fires onPress function when button is clicked
的{{1}}测试用例中,它能够找到按钮,但只有在模拟点击时它会显示:
SignUp.test.js
这是我要提供帮助的代码:
SignUp.js
Sign Up Page › fires onPress function when button is clicked
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
28 | // wrapper.find('#navigate').prop('onPress')();
29 | wrapper.find('#navigate').at(0).simulate('click');
> 30 | expect(onPress).toHaveBeenCalled();
| ^
31 | });
32 | });
33 |
SignUp.test.js
const SignUp = ({ navigation }) => {
const navigateOnPress = () => navigation.navigate('SignIn');
return (
<View style={Styles.container}>
<Text>SignUp</Text>
<Button
id="navigate"
title="Press me"
onPress={navigateOnPress}
/>
</View>
);
};
答案 0 :(得分:0)
通过直接调用onPress属性并查看是否调用了传递给该属性的函数来解决。
it('fires onPress function when button is clicked', () => {
const navigateToNextPage = jest.fn();
const props = {
navigation: {
navigate: navigateToNextPage,
},
};
const wrapper = shallow(<SignUp {...props} />);
wrapper.find('#navigate').first().props().onPress();
expect(navigateToNextPage).toHaveBeenCalledTimes(1);
});