Get Typescript object from Jest mock

Viewed 25

I am trying to test a particular scenario with help of jest.

SomeClient is exported as a non default class from the some/module and has a constructor and one of the methods like

SomeClient(string endpoint, string token) and getProperties(): Promise<Properties>

ConnectivityManager has a method isConnected whose signature is like

public static async isConnected(someClient: SomeClient): Promise<boolean> which also calls someClient.getProperties()

In test class ConnectivityManager.test.ts my code is like this

import { SomeClient } from 'some/module';

jest.mock('some/module', () => {
      return {
        SomeClient: jest.fn().mockImplementation(() => {
          return {
            getProperties: (): Promise<Properties> =>
              new Promise((resolve) => {
                resolve(mockResponseObject);
              })
          };
        })
      };
    });

test('isConnected should be able to return true if SomeClient returns Properties', async () => {
  const result = await ConnectivityManager.isConnected(someClientMock); 
  //someClientMock how do I get the mock object of type SomeClient to pass here?
}

How do I get the mock object of type SomeClient to pass to ConnectivityManager.isConnected?

1 Answers

You do not need to have such a complex way of mocking if your ConnectivityManager.isConnected uses only the SomeClient.getProperties.

You can do the following:

import { SomeClient } from 'some/module';

test('isConnected should be able to return true if SomeClient returns Properties', async () => {
  //setup
  const someClientMock = { getProperties: () => Promise.resolve(mockResponseObject) } as any as SomeClient;
  //act
  const result = await ConnectivityManager.isConnected(someClientMock); 
  //assert
  expect(result).toBe(true);
}

Related