【问题标题】:jest.fn() is being called multiple timesjest.fn() 被多次调用
【发布时间】:2019-01-28 12:22:36
【问题描述】:

我正在使用 jest 和酶测试我的 react-native 应用程序组件。为了监视作为道具传递的函数,我使用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')
  • 没错!我想我意识到了真正的问题。我认为这段代码是线性工作的,但事实证明不是。 spy 被调用的次数与在 describe 块中遇到的 it 块一样多。感谢@RuChernChong 的快速回答!

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


【解决方案1】:

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

你的beforeEach() 运行的次数是你有it() 的次数

【讨论】:

    猜你喜欢
    • 2019-07-20
    • 1970-01-01
    • 2020-06-08
    • 2010-10-24
    • 2011-10-18
    • 2020-10-19
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多