Col*_*ini 8 testing reactjs jest enzyme
我想测试一下,当从React组件调用一个方法时,它会触发一个函数传递给组件作为道具.方法是这样的:
customMethod() {
// Do something
this.props.trackEvent({
category: 'eventCategory',
action: 'eventAction',
label: 'eventAction',
});
// Do something else
}
Run Code Online (Sandbox Code Playgroud)
可以通过不同的方式调用该方法,因此我只想进行一般测试:如果调用了customMethod,则应该使用数据触发this.props.trackEvent.
有没有办法用jest和/或酶触发方法调用?我读到过这样的事情:
const wrapper = shallow(<AdPage {...baseProps} />);
wrapper.instance().customMethod();
Run Code Online (Sandbox Code Playgroud)
但它不起作用......任何想法.我在测试中很新,所以我应该使用不同的方法进行这种测试?
nbk*_*ope 14
假设你的customMethod是一个组件方法,我会像这样测试它:
(1)jest.fn()在创建包装器时伪造trackEvent prop .
(2)使用调用customMethod 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',
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9520 次 |
| 最近记录: |