简体   繁体   中英

Typescript expects mockImplementation to supply mocks for all methods and properties

I'm using typescript + jest, and am running into some type checking issues while creating mock implementations. As an example, I'd like to mock the Credentials object from the aws-sdk :

import { Credentials } from "aws-sdk";

jest.mock("aws-sdk");

const CredentialsMock = mocked(Credentials);

describe("Foo test", () => {
  beforeAll(() => {
    CredentialsMock.mockImplementation(() => { /*** <--- Type checking fails here ***/
      return {
        get: jest.fn()
      }
    });
  });
});

The problem I'm having is that the type checker wants me to supply mocks for every method/property of the Credentials type, when I just want to mock a single method. The specific error is:

TS2345: Argument of type '() => { get: jest.Mock; }' is not assignable to parameter of type '(accessKeyId: string, secretAccessKey: string, sessionToken?: string | undefined) => Credentials'.

Type '{ get: Mock; }' is missing the following properties from type 'Credentials': getPromise, needsRefresh, refresh, refreshPromise, and 5 more.

Is there a way to make typescript happy here?

One way I've found to make typescript happy, when providing a mock impementation that differs in arguments or return value from the original, is to wrap the mocked instance in a type assertion . Assuming that mocked(Credentials) in your example returns a jest.MockInstance , the type assertion would look like this:

    (CredentialsMock as jest.MockInstance<any, any>).mockImplementation(() => {
      return {
        get: jest.fn()
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM