2
votes

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?

1

1 Answers

2
votes

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()
      }
    });