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

标签 reactjs testing enzyme jestjs

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

customMethod() {
  // Do something

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

  // Do something else
}

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

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

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

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

最佳答案

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

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

(2) 使用 wrapper.instance().customMethod();

调用您的自定义方法

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

举个例子:

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',
  });
}); 

关于reactjs - 测试 React 组件方法正在调用函数 pass 作为 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45867095/

相关文章:

javascript - 如何在react中转换&lt;script&gt;标签?

c++ - mbed OS 5 项目中链接了哪些文件?

java - 如何从命令行在 JUnit 4 中运行也被忽略的测试?

javascript - 由于使用 'addEventListener' 导入的脚本, enzyme 无法浅渲染

javascript - 第二次尝试时 react 函数松散状态

javascript - 如何在另一个调用this.setState()的函数内部的函数中访问组件的状态?

javascript - 如何使用 React-Bootstrap 模态

testing - 需要有关在 Meteor.js 中使用 Chimp.js/Mocha 进行测试的建议

javascript - 开 Jest/ enzyme 测试 : this. props.showOverlay 不是函数

javascript - 使用 enzyme full mount 找到的组件实例等于 null