How to cast properly a mock function with Typescript

Viewed 232

I'm trying to mock a function and use the benefits from Typescript but I can't find the best way to do it. A bit of context, I want to test a class who use a Keycloak instance. This is the case:

import keycloak from 'keycloak-js';
import { Auth } from './auth';

jest.mock('keycloak-js');

const keycloakMock = keycloak as jest.MockedFunction<typeof keycloak>;
...
// This is what I want to use it, because TS autocomplete the methods and helps me.
keycloakMock.mockImplementation(() => ({ init: jest.fn().mockResolvedValue(true) }));
// but also, the TS compiler said:

Type '{ init: Mock<any, any>; }' is missing the following properties from type 'KeycloakInstance': login, logout, register, accountManagement, and 11 more.ts(2740) index.d.ts(1163, 33): The expected type comes from the return type of this signature.

What I'm doing wrong? Because I test to set a //@ts-ignore and the test pass, but I don't like this solution. Also if I declare the keycloakMock like this:

const keycloakMock = keycloak as jest.Mock;

Works, but without types... I tried to follow the guide from Jest about the MockedFunctions but I can't figure out how to solve it.

I'm using the following versions (if these can helps, in some way?)

    "@types/jest": "^25.2.1",
    "jest": "^26.0.0",
    "ts-jest": "^26.4.4",
    "typescript": "~3.9.5",
    "keycloak-js": "^11.0.2"
0 Answers
Related