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?
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.
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
      }))
    }
  }});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With