jest.fn()被多次调用

时间:2019-01-28 12:22:36

标签: javascript unit-testing react-native jestjs enzyme

我正在用玩笑和酵素测试我的本机应用程序组件。为了监视作为道具传递的函数,我使用了jest.fn()。运行测试时,出现错误提示Expected mock function to have been called one time, but it was called two times。测试onPress方法时出现此错误。

我尝试删除匿名函数来调用组件中的prop方法;直接引用组件内部的onPress的{​​{1}}方法,而无需从组件的prop调用它;在测试用例之前重新渲染测试组件。但是没有成功。

<TouchableOpacity/>

此外,当我在/*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); }); }); 内部直接调用spy()时,它也被调用了2次。

1 个答案:

答案 0 :(得分:0)

wrapper.prop('navigate')函数中取出beforeEach()

您的beforeEach()正在运行的次数为it()