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?
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);
}
}
}
});
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'),
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With