如何在 Typescript 中模拟 Cognito 响应
Posted
技术标签:
【中文标题】如何在 Typescript 中模拟 Cognito 响应【英文标题】:How to mock Cognito response in Typescript 【发布时间】:2021-08-27 22:22:46 【问题描述】:定义class CognitoPool
后保存为cognitoPool.ts
脚本:
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());
我继续写一个测试脚本:
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');
)
)
mockData
将由 identityService.listUsers()
返回为 as PromiseResult
:
let mockData =
Users: []
as unknown as PromiseResult<any, AWSError>;
但测试脚本运行时出现错误:
TypeError: this.identityService.listUsers(...).promise is not a function
有没有办法避免这个错误?
【问题讨论】:
【参考方案1】:PromiseResult
是一个包含.promise
作为函数的对象。然后,当你想模拟一个函数返回一个PromiseResult
,模拟数据应该是一个像PromiseResult
这样的对象。
在您的情况下,mockData
应该是:
const mockData =
promise: () => Promise.resolve( Users: [] ),
as unknown as PromiseResult<any, AWSError>;
【讨论】:
以上是关于如何在 Typescript 中模拟 Cognito 响应的主要内容,如果未能解决你的问题,请参考以下文章
如何在 TypeScript 中使用 mocha 模拟 axios 依赖项?
如何使用 jest.fn() 在 jest 中使用 typescript 模拟函数
Typescript / Node.js - 如何模拟集成测试的传递依赖项?