How to mock a dependency’s constructor with Jest?

Sometimes, we want to mock a dependency’s constructor with Jest.

In this article, we’ll look at how to mock a dependency’s constructor with Jest.

How to mock a dependency’s constructor with Jest?

To mock a dependency’s constructor with Jest, we can call jest.mock.

For instance, we write

import * as AWS from 'aws-sdk';

jest.mock('aws-sdk', () => {
  return {
    CloudWatch: jest.fn().mockImplementation(() => {
      return {}
    })
  }
});

test('AWS.CloudWatch is called', () => {
  new AWS.CloudWatch();
  expect(AWS.CloudWatch).toHaveBeenCalledTimes(1);
});

to mock the CloudWatch constructor with a function that returns an empty object.

We call jest.fn to return a mocked function and we mock the return value of the function with mockImplementation.

Then we can use the AWS.CloudWatch constructor to run the mocked version of the constructor.

We still have to import the real dependency with

import * as AWS from 'aws-sdk';

before we can mock AWS.CloudWatch.

Conclusion

To mock a dependency’s constructor with Jest, we can call jest.mock.