3

I'm writing unit tests for a serverless application in TypeScript, and I'd like to mock the AWS SDK.

Unfortunately I have not found many existing type definitions for popular AWS mocking projects. In particular I'd like to use the aws-sdk-mock library, but without its type definitions I can't.

Theoretically I'd like to be able to do something like:

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');
    });
  });
});
rawkfist0215
  • 1,445
  • 6
  • 21
  • 34

1 Answers1

1

Here's how we got it working with jest. This tests a lambda function that makes calls to Dynamo using the DynamoDB.DocumentClient.

The warnings about importing the aws-sdk-mock ts definitions go away for me if the file is called *.test.ts or *.spec.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");
  });
});
adanilev
  • 3,008
  • 3
  • 15
  • 20