2

I have the following jest test configuration for my collection of AWS JS Node Lambdas. I have a module called dynamoStore I reference in several different lambdas package.json and use within the lambdas. I am trying to get test one of these lambdas by mocking the dynamo store module as it makes calls to dynamoDb. The problem is that the jest.fn implementation never gets called. I confirmed this by sticking a breakpoint in that line as well as logging the value the calling methods returns from it.

When I check lambda1/index.js in the debugger getVehicleMetaKeysFromDeviceId() is a jest object but when it is called it doesn't use my mock implementation

How do I get this implementation to work? Have I set up my mock incorrectly?

dynamoStore/vehicleMetaConstraints

exports.getVehicleMetaKeysFromDeviceId= async (data) => {
  return data
};

dynamoStore/index.js

exports.vehicleMetaConstraints = require("./vehicleMetaConstraints");
...

lambda1/index.js

const { vehicleMetaStore } = require("dynamo-store");

exports.handler = async (event, context, callback) => {
    const message = event;
  
    let vehicle_ids = await vehicleMetaStore.getVehicleMetaKeysFromDeviceId(message.id);
    // vehicle_ids end up undefined when running the test
}

lambda1/index.test.js

const { vehicleMetaStore } = require("dynamo-store");

jest.mock("dynamo-store", () => {
  return {
    vehicleMetaStore: {
      getVehicleMetaKeysFromDeviceId: jest.fn(),
    },
  };
});

describe("VehicleStorageLambda", () => {
  beforeEach(() => {
    jest.resetModules();
    process.env = { ...env };
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  test("Handles first time publish with existing device", async () => {
    let functionHandler = require("./index");
    vehicleMetaStore.getVehicleMetaKeysFromDeviceId.mockImplementationOnce(() =>
      // This never gets called
      Promise.resolve({
        device_id: "333936303238510e00210022",
      })
    );

    await functionHandler.handler({});
  });
});

1 Answers1

0

Remove the call to jest.resetModules() in beforeEach. That's re-importing your modules before each test, and wiping out your mocks.

https://stackoverflow.com/a/59792748/3084820

Matt Morgan
  • 4,900
  • 4
  • 21
  • 30