Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock AWS Cognito CognitoIdentityServiceProvider with Jest?

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?

like image 772
eudaimonia Avatar asked Oct 15 '25 01:10

eudaimonia


2 Answers

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);
        }
      }
    }
});
like image 123
eudaimonia Avatar answered Oct 17 '25 16:10

eudaimonia


Here's another way to do it if we want to use spyOn to mock a specific function:

const cognotoIdentityServiceProvider = Object.getPrototypeOf(new AWS.CognitoIdentityServiceProvider());
const stub = jest.spyOn(cognotoIdentityServiceProvider, 'adminDeleteUser').mockReturnValue({
  promise: () => Promise.resolve('bob johnson'),
});
like image 21
Justin Avatar answered Oct 17 '25 16:10

Justin