In Jest, a common scenario for testing a React component involves using mocks to simulate the behavior of functions, modules, or contexts that your component depends on. If by "mock hocs" you mean "mocking Higher-Order Components" (HOCs), here's a guide on how to do that.
Steps to Mock a Higher-Order Component (HOC) in Jest
-
Understand the HOC: A HOC is a function that takes a component and returns a new component. When testing, you might want to replace the HOC with a mock or a simpler version of it.
-
Create a Mock for the HOC: You can create a simple mock implementation that wraps the child component without adding any additional logic.
-
Write Your Test: Use Jest and React Testing Library (or Enzyme) to write your test.
Example
Suppose you have an HOC called withAuth that provides authentication props to a component.
// withAuth.js
import React from 'react';
const withAuth = (WrappedComponent) => {
return (props) => {
const isAuthenticated = true; // Assume logic to determine authentication
return <WrappedComponent {...props} isAuthenticated={isAuthenticated} />;
};
};
export default withAuth;
And you have a component that uses this HOC:
// MyComponent.js
import React from 'react';
import withAuth from './withAuth';
const MyComponent = ({ isAuthenticated }) => {
return <div>{isAuthenticated ? 'Logged In' : 'Logged Out'}</div>;
};
export default withAuth(MyComponent);
Mocking the HOC in Tests
First, create a mock for the HOC:
// __mocks__/withAuth.js
import React from 'react';
const mockWithAuth = (WrappedComponent) => {
return (props) => <WrappedComponent {...props} isAuthenticated={true} />;
};
export default mockWithAuth;
Now, use the mock in your test file:
// MyComponent.test.js
import React from 'react';
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';
// Automatically mock the HOC
jest.mock('./withAuth');
describe('MyComponent', () => {
it('displays "Logged In" when isAuthenticated is true', () => {
const { getByText } = render(<MyComponent />);
expect(getByText('Logged In')).toBeInTheDocument();
});
});
Important Notes
-
Automatic Mocking: The line jest.mock('./withAuth'); automatically uses the mock defined in __mocks__/withAuth.js. Make sure your mock file is correctly placed in a __mocks__ directory at the same level as your withAuth.js file.
-
Custom Props: If you need to test with different props, you can modify the mock implementation or directly pass different props when rendering.
-
Assertions: Use assertions to verify the behavior of the component based on what the HOC is supposed to provide (like authenticated states).
By following these steps, you can effectively mock HOCs in your Jest tests, allowing for focused unit testing of your components while isolating them from dependencies.