我正在用jest和酶测试我的反应原生应用程序组件。为了监视作为道具传递的函数,我正在使用jest.fn()
.当我运行测试时,我收到错误说Expected mock function to have been called one time, but it was called two times
。测试onPress
方法时出现此错误。
我尝试删除在我的组件中调用 prop 方法的匿名函数; 直接引用组件内部<TouchableOpacity/>
onPress
方法,而无需从组件的 prop 调用它;在测试用例之前重新渲染测试组件。但没有成功。
/*BackButton.js*/
import React from 'react';
import { TouchableOpacity } from 'react-native';
import { Icon } from 'expo';
import { iconStyle, Colors } from '../constants';
const styles = {
icon: {
marginLeft: 5,
color: Colors.white,
fontSize: 40
}
};
function BackButton(props) {
return (
<TouchableOpacity
onPress={()=>props.navigate()}
style={{width: 50}}
>
<Icon.Ionicons
name={`${iconStyle}-refresh`}
style={styles.icon}
/>
</TouchableOpacity>
);
}
export default BackButton;
=======================================
/*BackButton-test.js*/
import 'react-native';
import React from 'react';
import {mount} from 'enzyme';
import BackButton from '../BackButton';
describe('navigate action', () => {
const spy = jest.fn();
const wrapper = mount(<BackButton navigate={spy}/>);
it('renders correctly', () => {
expect(wrapper).toMatchSnapshot();
});
beforeEach(() => {
wrapper.prop('navigate')();
});
it('calls once', () => {
expect(spy).toHaveBeenCalledTimes(1);
});
});
而且,当我直接在beforeEach
里面打电话spy()
时,它也被叫了2次。
从beforeEach()
函数中取出wrapper.prop('navigate')
您的beforeEach()
正在运行的次数是it()