用玩笑嘲笑高阶组件 [英] Mocking a higher order component with jest
问题描述
我想确保使用笑话来调用HOC组件,但是我似乎无法使jest.mock
正常工作.我的HOC是这样的:
I want to ensure that a HOC component is being called with jest, but I can't seem to get jest.mock
to work. My HOC is like this:
const withEntity = (
...args
) => {
const wrappedComponent = WrappedComponent => {
const innerComponent = ({ ...props }) => {
return (
<WrapperComponent
{...props}
>
<WrappedComponent />
</WrapperComponent>
);
};
innerComponent.propTypes = {
...
};
return innerComponent;
};
wrappedComponent.propTypes = {
...
};
return wrappedComponent;
};
withEntity.propTypes = {
...
};
export default withEntity;
在一个单独的文件中,withEntity
函数的调用方式如下:
In a separate file, the withEntity
function is called like this:
export const DoSomething = withEntity(...args)(MyComponent);
然后,在DoSomething
组件的测试文件中,我试图导入withEntity
函数并对其进行模拟,如下所示:
Then, in the testing file for the DoSomething
component, i'm trying to import the withEntity
function and mock it like so:
import withEntity from "../../../shared/entity/higher_order_components/withEntity";
jest.mock("../../../shared/entity/higher_order_components/withEntity");
但是当我实际尝试运行测试时,出现此错误:
But when I actually attempt to run the test, I get this error:
● Test suite failed to run
TypeError: (0 , _withEntity.default)(...) is not a function
不确定导致该错误的原因是什么,我在这里做错了什么?
Not sure what to make of that error, what am I doing wrong here?
推荐答案
模拟您的HOC应该如下所示:
Mocking your HOC should look like this:
jest.mock('../your/HOC', () => () =>
Component => props => <Component {...props} />
)
它可以读为:
jest.mock('../your/HOC', () => `
创建一个返回您的HOC函数的模拟程序,
create a mock that returns your HOC function,
() =>
返回您的HOC aka withEntity(...args)
,
the function that returns your HOC aka withEntity(...args)
,
Component => props => <Component {...props} />
HOC本身是一个函数,该函数获取组件并返回一个函数,该函数获取道具,并返回一个函数,该函数返回具有其道具的渲染组件.
the HOC itself, which is a function that gets the component and return a function that get the props and return a function that returns the rendered component with its props.
这篇关于用玩笑嘲笑高阶组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!