How to mock AWS TimestreamWrite by jest

This project is to record data by AWS Timestream, and it works well.

However, I'm failed to mock AWS TimestreamWrite by using jest. I tried some ways but not working. Can someone help me?

My files as below:

ledger-service.js

const AWS = require("aws-sdk");
const enums = require("./enums");

var https = require("https");
var agent = new https.Agent({
  maxSockets: 5000,
});
const tsClient = new AWS.TimestreamWrite({
  maxRetries: 10,
  httpOptions: {
    timeout: 20000,
    agent: agent,
  },
});

module.exports = {
  log: async function (audit) {
    try {
      if (Object.keys(audit).length !== 0) {
        if (!isPresent(audit, "name")) {
          throw new Error("Name shouldn't be empty");
        }

        if (!isPresent(audit, "value")) {
          throw new Error("Value shouldn't be empty");
        }

        return await writeRecords(recordParams(audit));
      } else {
        throw new Error("Audit object is empty");
      }
    } catch (e) {
      throw new Error(e);
    }
  },
};
function isPresent(obj, key) {
  return obj[key] != undefined && obj[key] != null && obj[key] != "";
}
function recordParams(audit) {
  const currentTime = Date.now().toString(); // Unix time in milliseconds
  const dimensions = [
    // { Name: "client", Value: audit["clientId"] },
    { Name: "user", Value: audit["userId"] },
    { Name: "entity", Value: audit["entity"] },
    { Name: "action", Value: audit["action"] },
    { Name: "info", Value: audit["info"] },
  ];

  return {
    Dimensions: dimensions,
    MeasureName: audit["name"],
    MeasureValue: audit["value"],
    MeasureValueType: "VARCHAR",
    Time: currentTime.toString(),
  };
}
function writeRecords(records) {
  try {
    const params = {
      DatabaseName: enums.AUDIT_DB,
      TableName: enums.AUDIT_TABLE,
      Records: [records],
    };

    return tsClient.writeRecords(params).promise();
  } catch (e) {
    throw new Error(e);
  }
}

ledger-service.spec.js

const AWS = require("aws-sdk");
const audit = require("./ledger-service");

describe("ledger-service", () => {

    beforeEach(async () => {
        jest.resetModules();
    });
  
    afterEach(async () => {
      jest.resetAllMocks();
    });

    it("It should write records when all success", async () => {
        const mockAudit={
            name: 'testName',
            value: 'testValue',
            userId: 'testUserId',
            entity: 'testEntity',
            action: 'testAction',
            info: 'testInfo',
        };

        const mockWriteRecords = jest.fn(() =>{
            console.log('mock success')
            return { promise: ()=> Promise.resolve()}
         });

        const mockTsClient={
            writeRecords: mockWriteRecords
        }

        jest.spyOn(AWS,'TimestreamWrite');
        AWS.TimestreamWrite.mockImplementation(()=>mockTsClient);

        //a=new AWS.TimestreamWrite();
        //a.writeRecords();   //these two lines will pass the test and print "mock success"

        await audit.log(mockAudit); //this line will show "ConfigError: Missing region in config"

        expect(mockWriteRecords).toHaveBeenCalled();
    });
});

I just think the the AWS I mocked doesn't pass into the ledger-service.js. Is there a way to fix that?

Thanks



Read more here: https://stackoverflow.com/questions/67426453/how-to-mock-aws-timestreamwrite-by-jest

Content Attribution

This content was originally published by Ben at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: