目前正在尝试测试按钮'onPress'在单击后是否已被调用,但是我遇到了一些麻烦。在我的fires onPress function when button is clicked
测试用例中,它可以找到按钮以及除模拟点击之外的所有内容:
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>
);
};
通过直接调用onPress属性并查看是否调用了传递给该属性的函数来解决。
import React from 'react';
import { shallow } from 'enzyme';
import SignUp from '../../../components/SignUp/SignUp';
describe('Sign Up Page', () => {
function render(args) {
const defaultProps = {
navigation: {
navigate: jest.fn(),
},
};
const props = {
...defaultProps, ...args,
};
return shallow(<SignUp {...props} />);
}
it('renders the sign up page', () => {
const wrapper = render();
expect(wrapper).toMatchSnapshot();
});
it('fires onPress function when button is clicked', () => {
const wrapper = render();
const onPress = jest.fn();
wrapper.find('#navigate').prop('onPress')();
wrapper.find('#navigate').at(0).simulate('click');
expect(onPress).toHaveBeenCalled();
});
});