Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 673
Charklewis Avatar asked Jan 04 '21 00:01

Charklewis


People also ask

Does Jest work with TypeScript?

Jest supports TypeScript, via Babel. First, make sure you followed the instructions on using Babel above. Next, install the @babel/preset-typescript : npm.

How do you use spyOn function in Jest?

To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.

What is Jest fn () do?

The jest. fn method allows us to create a new mock function directly. If you are mocking an object method, you can use jest.


1 Answers

I am not sure if this helps but you may use mockedCookies.get.mockImplementationOnce(() => ({})) as of now to get rid of this error.

Updated: After some testing, I see that these mock functions are stored in dictionary style format. The last function with same name always replace the previous ones.

If you try to move get(name: string) below get() from 'js-cookie', you will see that this error is gone. So there is no way to get specific function with same name.

like image 156
BananZ Avatar answered Nov 03 '22 23:11

BananZ