Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my jest mock function implementation being called?

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({});
  });
});
like image 228
Chris Chevalier Avatar asked Dec 20 '25 16:12

Chris Chevalier


1 Answers

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

like image 200
Matt Morgan Avatar answered Dec 23 '25 06:12

Matt Morgan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!