Mocking AWS S3 used inside a module to be tested in Jest with TypeScript


I have a module where there is a function I want to test with Jest that uses S3. I want to mock S3, so I found this solution and tried to implement it. My code is something like the following:

myModule.ts

import AWS from 'aws-sdk';
const S3 = new AWS.S3();

export async function getObjectFromS3() {
  // ...
  console.log(S3); // { getObject: undefined, putObject: undefined }
  const object = S3.getObject(params).promise()
  // ...
}

myModule.test.ts

import { getObjectFromS3 } from "./myModule"

// Mock S3

const mockGetObject = jest.fn(() => ({
  promise: () => Promise.resolve({ Body: 'object' }),
}));
const mockPutObject = jest.fn(() => ({
  promise: () => Promise.resolve(),
}));

jest.mock('aws-sdk', () => {
  return {
    S3: jest.fn(() => ({
      getObject: mockGetObject,
      putObject: mockPutObject,
    })),
  };
});

// Test module

describe("...", () => {
  test("...", async () => {
    const result = await getObjectFromS3();
    expect(result).toBe("whatever");
  })
})

It says S3 does have getObject and putObject but both are undefined.

It occurred to me to make the AWS.S3 instance inside the function I’m testing, and in that case it does work and the test passes.

myModule.ts

import AWS from 'aws-sdk';

export async function getObjectFromS3() {
  // ...
  const S3 = new AWS.S3();
  console.log(S3); // { getObject: [Function: mockConstructor] {...}, putObject: [Function: mockConstructor] {...} }
  const object = S3.getObject(params).promise()
  // ...
}

But I don’t want to make a new instance of S3 in every function I need it.

How can I make the mock so that the properties of the global AWS.S3 instance (as in the first code) are not undefined?

Source: JavaSript – Stack Overflow

October 28, 2021
Category : News
Tags: javascript | jestjs | mocking | node.js | unit testing

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.