Reputation: 1247
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;
In a separate file, the withEntity
function is called like this:
export const DoSomething = withEntity(...args)(MyComponent);
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?
Upvotes: 8
Views: 10743
Reputation: 11
This works for me
.mock(
'./pathTo/yourHOC',
() => () => (Component) => {
return Component;
})
Upvotes: 0
Reputation: 536
What worked for me is basically putting the below snippet into setupTests.js if you wish the render your component without the HOC affecting it.
jest.mock('./pathTo/yourHOC', () => Component => {
return Component
})
Upvotes: 0
Reputation: 2701
In my case because I am using typescript this is what works for me.
jest.mock('components/MyComponent', () => ({
__esModule: true,
default({children}: any) {
return children(() => {});
},
}));
Upvotes: 1
Reputation: 110922
Mocking your HOC should look like this:
jest.mock('../your/HOC', () => () =>
Component => props => <Component {...props} />
)
it can be read as :
jest.mock('../your/HOC', () => `
create a mock that returns your HOC function,
() =>
the function that returns your HOC aka withEntity(...args)
,
Component => props => <Component {...props} />
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.
Upvotes: 18