I have a custom hook
import { useDispatch } from 'react-redux';
import { SET_APP_TITLE } from '../reducers/appBar';
export const useTitle = (title: string) => {
const dispatch = useDispatch();
return dispatch({ type: SET_APP_TITLE, title });
};
And component using it
import { useTitle } from '../common/useTitle';
export default () => {
useTitle('Dashboard');
return <div>Dashboard</div>
}
Now I want to write unit test (using Jest and React Testing Library) for the component:
import React from 'react';
import { render } from '@testing-library/react';
import Dashboard from './Dashboard';
import { useTitle } from '../commons/useTitle';
describe('Dashboard', () => {
it('renders without crashing', () => {
const { getByText } = render(<Dashboard />);
expect(getByText('Dashboard')).toBeInTheDocument();
});
});
In this test I'd like to spy on my custom hook and assert that the component tries to set valid title.
Use jest.mock(moduleName, factory, options) to mock
../commons/useTitle
module. TheuseTitle
custom hook will be mocked when you import and use it in your test file.E.g.
useTitle.ts
:Dashboard.tsx
:Dashboard.test.tsx
:unit test result with coverage report: