Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...