Mock "is not assignable to parameter of type '() => [unknown, Dispatch<unknown>]'"

Viewed 416

I need to mock the following useState hook using Jest and TypeScript:

const [myState, setMyState] = useState<MyType>(MyType.TYPE_0)

In my test, to mock it, I'm writing:

import * as React from 'react'

const setState = jest.fn();
const useStateSpy = jest.spyOn(React, 'useState');

useStateSpy.mockImplementation((init: MyType) => [init = MyType.TYPE_1, setState]);

However, since I'm using TypeScript, it's complaining that I'm not specifying the type of my spyOn.

Argument of type '(init: MyType) => (MyType | jest.Mock<any, any>)[]' is not assignable to parameter of type '() => [unknown, Dispatch<unknown>]'

I tried different approaches but I'm not able to correctly type my mocks.

How can I specify the type of setState and useStateSpy?

1 Answers

Initialize the value with some value

import * as React from 'react'

const setState = jest.fn();
const useStateSpy = jest.spyOn(React, 'useState');

useStateSpy.mockImplementation((init: MyType = **'Initial value'**) => [init = MyType.TYPE_1, setState]);
or 
useStateSpy.mockImplementation((init?: MyType) => [init = MyType.TYPE_1, setState]);
Related