可以将TypeScript与'aws-sdk-mock'一起使用

时间:2018-06-21 23:24:52

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

我正在用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');
    });
  });
});

2 个答案:

答案 0 :(得分:1)

这就是我们如何使其开玩笑地工作。这将测试一个lambda函数,该函数使用DynamoDB.DocumentClient调用Dynamo。

如果文件名为* .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");
  });
});

答案 1 :(得分:0)

您实际上并不需要类型定义-要进行“无类型香草JS”导入,使导入的模块any只需如上所述将import交换为const即可。 这对我有用:

const AWSMock = require('aws-sdk-mock');
import AWS = require('aws-sdk');
AWSMock.setSDKInstance(AWS);
AWSMock.mock('SQS', /* ... */);

const sqs = new AWS.SQS();
// test stuff