How to mock Cognito response in Typescript

Viewed 415

After defining class CognitoPool saving it as cognitoPool.ts script:

const AWS = require('aws-sdk');
import { CognitoIdentityServiceProvider } from 'aws-sdk';
import {ListUsersRequest, ListUsersResponse} from 'aws-sdk/clients/cognitoidentityserviceprovider';

export class CognitoPool {
  private identityService: CognitoIdentityServiceProvider;

  constructor(identityService: CognitoIdentityServiceProvider) {    
    this.identityService = identityService;
  }

  async listCognitoUsers(poolID: string, sub: string): Promise<ListUsersResponse> {

    let params = {
      UserPoolId: poolID,
      Filter: `sub="${sub}"`
    } as ListUsersRequest;

    let res: ListUsersResponse = await this.identityService.listUsers(params).promise();
    return res;
  }
}

export default new CognitoPool(new AWS.CognitoIdentityServiceProvider());

I go ahead and write a test script:

const AWS = require('aws-sdk');
import sinon, { stubObject } from 'ts-sinon'
import { CognitoIdentityServiceProvider, AWSError } from 'aws-sdk';
import { PromiseResult } from 'aws-sdk/lib/request';
import { CognitoPool } from './cognitoPool';


describe('Testing', () => {

  const identityService = new AWS.CognitoIdentityServiceProvider();

  const stub = stubObject(identityService);

  const cognitoPool = new CognitoPool(stub);

  it('Test 01', async () => {

    let mockData = {
      Users: []
    } as unknown as PromiseResult<any, AWSError>;
    
    stub.listUsers.returns(mockData); 

    let result = await cognitoPool.listCognitoUsers('poolId-123', 'sub-123');

  })

})

A mockData is to be returned by identityService.listUsers() as as PromiseResult:

    let mockData = {
      Users: []
    } as unknown as PromiseResult<any, AWSError>;

But a test script runs with an error:

TypeError: this.identityService.listUsers(...).promise is not a function

Is there a way to avoid this error?

1 Answers

PromiseResult is an object that includes .promise as a function. Then, when you want to mock a function to return a PromiseResult, the mock data should be an object like PromiseResult.

In your case, mockData should be:

const mockData = {
  promise: () => Promise.resolve({ Users: [] }),
} as unknown as PromiseResult<any, AWSError>;
Related