Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 361
vamsiampolu Avatar asked Sep 05 '19 18:09

vamsiampolu


2 Answers

This worked for me:

const mockDynamoDbPut = jest.fn().mockImplementation(() => {
  return {
    promise() {
      return Promise.resolve({});
    }
  };
});

jest.doMock('aws-sdk', () => {
  return {
    DynamoDB: jest.fn(() => ({
      DocumentClient: jest.fn(() => ({
        put: mockDynamoDbPut
      }))
    }))
  };
});

I hope it's helpful for you too.

Regards,

David.

like image 172
duxtinto Avatar answered Oct 03 '22 07:10

duxtinto


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
      }))
    }
  }});
like image 45
dpmott Avatar answered Oct 03 '22 08:10

dpmott