Ad

How Can I Test A Function Of A Function Component That Uses React.useState() Using Jest Enzyme Testing?

- 1 answer

I have a function component that uses React.useState() to manage the state of a drawer modal. I want to test the function the changes this state using jest enzyme, but I cannot call it's state function because it's not a class component.

The code I wish to test is below:

const [state, setState] = React.useState({
    drawerOpen: false,
});

function toggleDrawer(boolean) {
    setState({ ...state, drawerOpen: boolean });
}
<Button
       id="openDrawer"
       onClick={() => toggleDrawer(true)}
       style={{ margin: spacing.small }}
       >
       <AddIcon />
       {buttonText}
</Button>

And this is what would've worked if it was a class component:

it("should open the drawer on button click", () => {
        wrapper.find("#openDrawer").simulate("click");
        expect(wrapper.state("drawerOpen")).toBetruthy();
});

And yes, it should remain a function component.

Ad

Answer

Maybe it will be helpfull: Here is an mock util, that is basically a function that is going to accept state and return a tuple

export const setHookState = (newState: {}) => jest.fn().mockImplementation((state: {}) => [
   newState,
   (newState: {}) => {}
])

Then, in test, you just use it like this:

import { setHookState } from 'utils/test'
import { ComponentWithHook } from './ComponentWithHook'
import { NeededComponent } from './NeededComponent'
const reactMock = require('react')
describe('ComponentWithHook component', () => {
  it('should render itself', () => {
    reactMock.useState = setHookState({
        data: [],
        isFetching: false
    })
    const wrapper = shallow(<ComponentWithHook/>)
    expect(wrapper.find(<NeededComponent>).exists()).toEqual(true)
  })
})

Info from this source: here

Ad
source: stackoverflow.com
Ad