Skip to content

Instantly share code, notes, and snippets.

@natterstefan
Created February 18, 2020 14:47
Show Gist options
  • Save natterstefan/b9748dfe75f8ca177e25e50b3f466e9f to your computer and use it in GitHub Desktop.
Save natterstefan/b9748dfe75f8ca177e25e50b3f466e9f to your computer and use it in GitHub Desktop.
Jest | Mock useState

Jest - mock useState

When using import React, { useState } from 'react' in your components, this is how you can mock useState with jest.

// source: https://dev.to/ppciesiolkiewicz/comment/i708
import React, { useState as useStateMock } from 'react'
import { mount } from 'enzyme'
// Header uses `useState`
import { Header } from '..'
jest.mock('react', () => ({
...jest.requireActual('react'),
useState: jest.fn(),
}))
describe('Header', () => {
const setState = jest.fn()
beforeEach(() => {
useStateMock.mockImplementation(init => [init, setState])
})
it('renders', () => {
const wrapper = mount(
<Header />
)
expect(setState).toHaveBeenCalledTimes(1)
expect(wrapper).toBeTruthy()
})
})
// source: https://dev.to/ppciesiolkiewicz/comment/i708
import React, { useState as useStateMock } from 'react'
import { mount } from 'enzyme'
// Header uses `useState`
import { Header } from '..'
jest.mock('react', () => ({
...jest.requireActual('react'),
useState: jest.fn(),
}))
describe('Header', () => {
const setState = jest.fn()
beforeEach(() => {
;(useStateMock as jest.Mock).mockImplementation(init => [init, setState])
})
it('renders', () => {
const wrapper = mount(
<Header />
)
expect(setState).toHaveBeenCalledTimes(1)
expect(wrapper).toBeTruthy()
})
})
@DamengRandom
Copy link

Thank for help man 👍, I will give it a try.

@ilham-akbar-syd
Copy link

I can confirm that the second link from @natterstefan works for me. Don't forget the

.mockImplementation((x) => [x, () => null]); // ensures that the rest are unaffected

part to ensure all useState mocked in case you forget one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment