Categories
JavaScript Answers

How to mock a dependency’s constructor with Jest?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *