【问题标题】:Test React component method is calling function pass as a prop测试 React 组件方法正在调用函数传递作为道具
【发布时间】:2018-02-02 15:49:52
【问题描述】:

我想测试当从 React 组件调用方法时,它会触发一个函数作为道具传递给组件。 方法是这样的:

customMethod() {
  // Do something

  this.props.trackEvent({
    category: 'eventCategory',
    action: 'eventAction',
    label: 'eventAction',
  });

  // Do something else
}

方法可以通过不同的方式调用,所以我只想做一个通用的测试:如果customMethod被调用,应该用数据触发this.props.trackEvent。

有没有办法使用 jest 和/或酶来触发方法调用?我读过关于做这样的事情:

const wrapper = shallow(<AdPage {...baseProps} />);
wrapper.instance().customMethod();

但它不起作用……任何想法。 我是测试的新手,所以也许我应该对这种测试使用不同的方法?

【问题讨论】:

    标签: reactjs testing enzyme jestjs


    【解决方案1】:

    假设您的 customMethod 是一个组件方法,我会这样测试它:

    (1) 在创建包装器时将 trackEvent 道具伪装成 jest.fn()

    (2) 使用wrapper.instance().customMethod(); 调用您的customMethod

    (3) 确保 props.trackEvent 具有你提到的参数。

    举个例子:

    test('customMethod should call trackEvent with the correct argument', () => {
      const baseProps = {
        // whatever fake props you want passed to the component
        // ...
        trackEvent: jest.fn(),
      };
      const wrapper = shallow(<AdPage {...baseProps} />);
    
      wrapper.instance().customMethod();
    
      expect(baseProps.trackEvent).toHaveBeenCalledTimes(1);
    
      expect(baseProps.trackEvent).toHaveBeenCalledWith({
        category: 'eventCategory',
        action: 'eventAction',
        label: 'eventAction',
      });
    }); 
    

    【讨论】:

    • 我正朝着好的方向前进,但您节省了很多旅行。谢谢!
    猜你喜欢
    • 2019-04-18
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多