Friday, 8 January 2021

Typescript using the incorrect type with jest when there are multiple available

I am new to typescript and noticed a behaviour I wasn't expecting. When I go to mock a named import with the js-cookie package, it mocks a particular instance of the property, but incorrectly chooses the correct type to use.

import Cookies from "js-cookie"
import { mocked } from "ts-jest/utils"

jest.mock("js-cookie")
const mockedCookies = mocked(Cookies, true)

beforeEach(() => {
  mockedCookies.get = jest.fn().mockImplementation(() => "123")
})

it("SampleTest", () => {
  //this line throws an error as it is using a difference interface to check against
  mockedCookies.get.mockImplementationOnce(() => undefined)
  //continue test...
}

In the @types/js-cookies there are two definitions for this and it always uses the get() version when I reference it as mockCookie.get.<some-jest-function>. Hence, I get typescript errors saying Type 'undefined' is not assignable to type '{ [key: string]: string; }'..

/**
* Read cookie
*/
get(name: string): string | undefined;

/**
* Read all available cookies
*/
get(): {[key: string]: string};

I can fix this by always redeclaring the jest.fn() every time, but would prefer to use the handy jest functions (like mockImplementationOnce).

Am I doing something wrong? Is there a way to enforce which get type to use?



from Typescript using the incorrect type with jest when there are multiple available

No comments:

Post a Comment