How to mock AWS Cognito CognitoIdentityServiceProvider with Jest?

Issue

I’m trying to write unit test where I need to mock response of method from cognito service –
CognitoIdentityServiceProvider

I have the following working code calling the adminInitiateAuth operation

import * from AWS from 'aws-sdk'


const cognito = new AWS.CognitoIdentityServiceProvider();
const response = await cognito.adminInitiateAuth(expectedParams).promise();

// main functionality I want to test

and I want to have a spec where I try to mock this service as prerequisites


const mockResponse = {
  AuthenticationResult: {
    AccessToken: 'expected-token'
  }
}

jest.mock('aws-sdk', () => {
    return {
      CognitoIdentityServiceProvider: {
        adminInitiateAuth: () => {
          return mockResponse;
        }
      }
    }
});


this returns me an error

AWS.CognitoIdentityServiceProvider is not a constructor

How this can not be a constructor?
Do you have any ideas how to mock it?

Solution

I figured it out. It may be useful to someone

jest.mock('aws-sdk', () => {
    return {
      CognitoIdentityServiceProvider: class {
        adminInitiateAuth() {
          return this;
        }

        promise() {
          return Promise.resolve(mockResponse);
        }
      }
    }
});

Answered By – eudaimonia

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.