Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

jestjs - How to cast properly a mock function with Typescript

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"
question from:https://stackoverflow.com/questions/65602161/how-to-cast-properly-a-mock-function-with-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...