Search code examples
typescriptamazon-dynamodbjestjsaws-sdk-nodejsts-jest

Mock the constructor for AWS.DynamoDB.DocumentClient using jest


I have a function that looks like this:

function connect() {
   const secret = 'secret';
   const key = 'key';
   const region = 'region';
   const client = new AWS.DynamoDB({
      secret,
      key,
      region
   });'
   return new AWS.DynamoDB.DocumentClient({ service: client })
}

I would like to test the function connect. I have mocked the DynamoDB constructor like this:

// See https://stackoverflow.com/questions/47606545/mock-a-dependencys-constructor-jest
jest.mock('aws-sdk', () => {
  const DynamoDB = jest.fn().mockImplementation(() => {
    return {};
  });
  return {
    DynamoDB,
  };
});

However, this means that the DocumentClient constructor fails. How do I mock that as well?


Solution

  • Building on the comment from duxtinto above:

    In my case (and in the case of the OP if I'm reading it right), DynamoDB isn't being called as a function, but rather is an object with a DocumentClient field on it, so this worked for me:

    jest.mock('aws-sdk', () => {
      return {
        DynamoDB: { // just an object, not a function
          DocumentClient: jest.fn(() => ({
            put: mockDynamoDbPut
          }))
        }
      }});