Testing with Jest. How to mock Hooks dynamically.
In our current project we have some core hooks (self-made React hooks, I mean). Implementation should not touch us at this article. Everything what we should know a file with hooks is accessible by using a path alias @core/hooks
Usually we use hooks like that
import { useViewerType } from '@core/hooks'
useViewerType has 2 internal boolean values: isStaff and isUser
I had to find a way how to mock values to make them changeable for different test cases.
const mockedStuffValue = jest.fn()
const mockedUserValue = jest.fn()jest.mock('@core/hooks', () => ({
useViewerType: () => ({
isStaff: mockedStuffValue(),
isUser: mockedUserValue()
})
}))afterEach(cleanup)
afterAll(() => jest.unmock('@core/hooks'))
Since now you can dynamically change both arguments with using .mockImplementation()
describe('FormBody', () => {
const onSubmit = () => undefined it('it is User', () => {
mockedStuffValue.mockImplementation(() => false)
mockedUserValue.mockImplementation(() => true) const { container } = render(
<FinalForm onSubmit={onSubmit} render={() => <FormBody />} />
)
expect(container).toMatchSnapshot()
})
})
The approach with using file mocking jest.mock(‘@core/hooks’) and implementation mocking .mockImplementation() helps me to avoid unnecessary requests to server and avoid creating of heavy mocking files with responses.
Have a good testing!