【问题标题】:Mocking the same function in two different test blocks in Jest在 Jest 的两个不同测试块中模拟相同的功能
【发布时间】:2017-07-28 18:10:51
【问题描述】:

我有一个关于在 Jest 中创建函数模拟的问题。我的页面上有两个元素在我的 React 组件中调用不同的函数。这两个函数都调用同一个函数,该函数是从 props 传入的,onFieldChanged。我想模拟这两个元素的变化,并确认props.onFieldChanged被调用了。

当我编写第一个测试(下面的第一个测试)时,它以优异的成绩通过。当我编写第二个测试时,第二个测试通过了,但现在第一个测试失败了。基本上,我不能同时通过两个测试。我需要以某种方式重置模拟吗?有谁知道怎么做?

什么给了?

  describe('user selects checkbox', () => {
    props.onFieldChanged = jest.fn();
    const wrapper = shallow(<DateOptions {...props} />);
    it('calls the onFieldChanged function', () => {
      const element = wrapper.find('#addOneToStudyDays');
      element.simulate('change');
      expect(props.onFieldChanged).toHaveBeenCalled();
    });
  });

  describe('user types in input', () => {
    props.onFieldChanged = jest.fn();
    const wrapper = shallow(<DateOptions {...props} />);
    it('calls the onFieldChanged function', () => {
      const element = wrapper.find('#lowerTimeLimit');
      element.simulate('change');
      expect(props.onFieldChanged).toHaveBeenCalled();
    });
  });

【问题讨论】:

    标签: javascript unit-testing reactjs jestjs


    【解决方案1】:

    尝试将 jest.fn() 作为不同的变量传递:

      describe('user selects checkbox', () => {
        it('calls the onFieldChanged function', () => {
          const onFieldChanged = jest.fn();
          const wrapper = shallow(<DateOptions {...props, onFieldChanged} />);
          const element = wrapper.find('#addOneToStudyDays');
          element.simulate('change');
          expect(props.onFieldChanged).toHaveBeenCalled();
        });
      });
    
      describe('user types in input', () => {
        it('calls the onFieldChanged function', () => {
          const onFieldChanged = jest.fn();
          const wrapper = shallow(<DateOptions {...props, onFieldChanged} />);
          const element = wrapper.find('#lowerTimeLimit');
          element.simulate('change');
          expect(props.onFieldChanged).toHaveBeenCalled();
        });
      });
    

    【讨论】:

    • @MaxMillington 你总是可以窥探这两个被lowerTimeLimit和addOneToStudyDays调用的实例组件方法,然后检查这些方法是否调用了onFieldChanged :)
    • 我现在正在尝试通过const spy = jest.spyOn(wrapper.instance(), 'handleInputFieldChanged'); 然后期待已调用间谍。 handleInputFieldChanged 肯定会被调用(在那里扔了一些 console.logs)但它仍然在说 Expected mock function to have been called.
    • 奇怪的是,mock的handleInputFieldChanged调用了console.log,mock后应该什么都不做。
    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 2021-04-19
    • 2020-05-30
    • 2022-01-05
    • 2019-07-16
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    相关资源
    最近更新 更多