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!

--

--

--

I’m front-end developer and really passionate programmer, caring husband and pancake baker on Sundays. School teacher of computer studies in the past.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ilya Zykin

Ilya Zykin

I’m front-end developer and really passionate programmer, caring husband and pancake baker on Sundays. School teacher of computer studies in the past.

More from Medium

Typescript for the rescue

How to use Nullish Coalescing in JavaScript

How global TypeScript utilities work under the hood — Readonly<Type>

Using generics to create extensible components using Typescript