【问题标题】:Is it possible to use TypeScript with 'aws-sdk-mock'是否可以将 TypeScript 与“aws-sdk-mock”一起使用
【发布时间】:2018-06-21 23:24:52
【问题描述】:

我正在使用 TypeScript 为无服务器应用程序编写单元测试,并且我想模拟 AWS 开发工具包。

不幸的是,我没有为流行的 AWS 模拟项目找到很多现有的类型定义。特别是我想使用aws-sdk-mock 库,但没有它的类型定义我不能。

理论上我希望能够做类似的事情:

import 'jest';
import * as sinon from 'sinon';
import * as _ from 'lodash';
import { handler } from '../lib/lambda';
import AWSMock from 'aws-sdk-mock';
import { PutItemInput } from 'aws-sdk/clients/dynamodb';

const mockData: DataType = {
   // ...some fields
};

describe('create data lambda tests', () => {

  afterEach(() => {
    sinon.restore();
    AWSMock.restore();
  });

  it('returns a success response on creation', () => {
    AWSMock.mock('DynamoDB.DocumentClient', 'put', (params: PutItemInput, callback: any) => {
      return callback(null, 'Successful creation');
    });

    const mockGatewayEvent: any = {
      headers: {
        Authorization: // some JWT
      },
      body: _.clone(mockData)
    };

    handler(mockGatewayEvent).then((createdData: DataType) => {
      expect(createdData.id).toBeDefined();
      expect(createdData.id.length).toBeGreaterThan(0);
    }, () => {
      fail('The create request should not have failed');
    });
  });
});

【问题讨论】:

    标签: amazon-web-services unit-testing typescript aws-lambda aws-sdk


    【解决方案1】:

    这是我们如何让它与 jest 一起工作的。这将测试一个使用 DynamoDB.DocumentClient 调用 Dynamo 的 lambda 函数。

    如果文件被称为 *.test.ts 或 *.spec.ts,关于导入 aws-sdk-mock ts 定义的警告就会消失。

    // stubbed.test.ts
    
    // this line needs to come first due to my project's config
    jest.mock("aws-sdk");
    
    import * as AWS from "aws-sdk-mock";
    import { handler } from "../index";
    // these next two are just test data
    import { mockDynamoData } from "../__data__/dynamo.data";
    import { mockIndexData } from "../__data__/index.data";
    
    describe("Stubbed tests", () => {
      it("should return correct result when Dynamo returns one slice", async () => {
        expect.assertions(2);
        const mockQuery = jest.fn((params: any, cb: any) =>
          cb(null, mockDynamoData.queryOneSlice)
        );
        AWS.mock("DynamoDB.DocumentClient", "query", mockQuery);
        // now all calls to DynamoDB.DocumentClient.query() will return mockDynamoData.queryOneSlice
    
        const response = await handler(mockIndexData.handlerEvent, null, null);
    
        expect(mockQuery).toHaveBeenCalled();
        expect(response).toEqual(mockIndexData.successResponseOneSlice);
    
        AWS.restore("DynamoDB.DocumentClient");
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-28
      • 2018-01-22
      • 2018-11-24
      • 2022-12-16
      • 2019-07-24
      • 2021-08-21
      • 2020-11-06
      • 1970-01-01
      相关资源
      最近更新 更多