Home > Blockchain >  Mock 'S3' feature of 'aws-sdk' (nodeJS and Jest)
Mock 'S3' feature of 'aws-sdk' (nodeJS and Jest)

Time:05-07

I need to test a file in charge of retrieving data from S3 through the 'aws-sdk' (nodeJs Jest). The file is:

const AWS = require('aws-sdk');

let S3 = null;

const getS3 = async () => {
  if (S3 === null) {
    const config = {
      endpoint: new AWS.Endpoint(process.env.S3_URL),
      s3ForcePathStyle: true,
    };
    S3 = new AWS.S3(config);
  }
  return S3;
};

module.exports.getObjectList = async (prefix) => {
  const params = {
    Bucket: process.env.S3_BUCKET,
    Delimiter: '/',
    Prefix: prefix,
  };
  const s3 = await getS3();
  const objectList = s3
    .listObjects(params)
    .promise()
    .then((data) => {
      const keys = data.Contents.map((c) => c.Key);
      return keys;
    })
    .catch((err) => {
      console.error(err);
      return null;
    });
  return objectList;
};


and the test file is as below :

const s3Client = require('./s3Client');

const mockS3Instance = {
  listObjects: jest.fn().mockReturnThis(),
  promise: jest.fn().mockReturnThis(),
  catch: jest.fn(),
};

jest.mock('aws-sdk', () => {
  return {
    S3: jest.fn(() => mockS3Instance),
    Endpoint: jest.fn(() => {
      'blabla';
    }),
  };
});

describe('s3Client tests', () => {
  it('basic test', async () => {
    const getObjectListResult = await s3Client.getObjectList('test');
    expect(1).toBe(1);
  });
});

But a error message is returned :

ypeError: s3.listObjects(...).promise(...).then is not a function

CodePudding user response:

You need to add a then mock in your mockS3Instance object

CodePudding user response:

Thanks to @gear4 reply, I was able to fix my code : (main part is about the promise returned from the mock)

const s3Client = require('./s3Client');

const mockS3Instance = {
  listObjects: jest.fn().mockReturnThis(),
  promise: jest.fn(() => {
    return new Promise((resolve, reject) => {
      return resolve({
        Contents: [{ Key: 'test-file-1' }, { Key: 'test-file-2' }],
      });
    });
  }),
  catch: jest.fn(),
};

jest.mock('aws-sdk', () => {
  return {
    S3: jest.fn(() => mockS3Instance),
    Endpoint: jest.fn(() => {
      'blabla';
    }),
  };
});

describe('s3Client tests', () => {
  it('Dummy tests: to be implemented', async () => {
    const getObjectListResult = await s3Client.getObjectList('test');
    expect(JSON.stringify(getObjectListResult)).toBe(
      JSON.stringify(['test-file-1', 'test-file-2']),
    );
  });
});
  • Related