[英]How to test HOC using react testing library
I have a HOC, adding some props to the component, for handling network requests and passing down data as prop.我有一个 HOC,向组件添加一些道具,用于处理网络请求并将数据作为道具传递。 The following is a very simplified version of the HOC:下面是一个非常简化的 HOC 版本:
export const withTags = (Component) => {
class WithTags extends PureComponent {
getItems() {
return getTags({
search: this.state.searchTerm
})
.then((items) => this.setState({
items
}));
}
.
.
.
render() {
return (
<Component
{...this.props}
items={this.state.items}
getItems={this.getItems}
/>
);
}
}
return withTags;
}
Using enzyme
I can easily do something like:使用enzyme
我可以很容易地做这样的事情:
it('should return tags', async () => {
const mockComponent = jest.fn(() => null);
const WithTagsComponent = withTags(mockComponent);
const wrapper = shallow(<WithTagsComponent />);
const res = await wrapper.props().getItems();
expect(res).toEqual(getTagsResponseMock);
expect(tagsApi.getTags).toHaveBeenCalledTimes(1);
expect(tagsApi.getTags).toHaveBeenCalledWith({
limit: PAGE_SIZE,
});
expect(wrapper.props().items).toEqual([tagFlowMock]);
});
But this approach won't work in React Testing Library, as we should test from the end-user's perspective, and not access props.但是这种方法在 React 测试库中不起作用,因为我们应该从最终用户的角度进行测试,而不是访问 props。 So, how should I test such HOCs using React Testing Library?那么,我应该如何使用 React 测试库来测试这样的 HOC?
I think your test almost works fine but you need to replace two things.我认为您的测试几乎可以正常工作,但是您需要替换两件事。 Since you're manually calling getItems
here you could create a mock Component that would ideally do similar stuff as the components you plan to use with your HOC.由于您在此处手动调用getItems
,因此您可以创建一个模拟组件,该组件在理想情况下会与您计划与 HOC 一起使用的组件执行类似的操作。 For example, this mock component coould have a button that when clicked would call getItems
and would also display items
.例如,这个模拟组件可以有一个按钮,单击该按钮会调用getItems
并且还会显示items
。
const MockComponent = ({items, getItems}) => {
return (
<div>
<button data-testid="button" onClick={getItems}>Click me</button>
<ul>
{ items.map((item, index) => <li key={index}>{item}</li>) }
</ul>
</div>
)
Then in your test instead of manually calling getItems
:然后在您的测试中,而不是手动调用getItems
:
const res = await wrapper.props().getItems();
you could do something like你可以做类似的事情
fireEvent.click(getByTestId('button')
and then assert that your tagsApi was called and that your component displays correct items.然后断言您的 tagsApi 被调用并且您的组件显示正确的项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.