我想测试一下,当从 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/