测试 React 组件方法正在调用函数 pass 作为 prop

Test React component method is calling function pass as a prop

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

customMethod() {
  // Do something

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

  // Do something else
}

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

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

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

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

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

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

(2) 使用 wrapper.instance().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',
  });
});