mocking nodemodules which return a function with jest?

I came across an answer in this issue thread for ts-jest. Apparently, ts-jest does NOT “hoist” variables which follow the naming pattern mock*, as regular jest does. As a result, when you try to instantiate a named mock variable before using the factory parameter for jest.mock(), you get an error that you cannot access the mock variable before initialization.

Per the previously mentioned thread, the jest.doMock() method works in the same way as jest.mock(), save for the fact that it is not “hoisted” to the top of the file. Thus, you can create variables prior to mocking out the library.

Thus, a working solution is as follows:

const mockLogin = jest.fn().mockImplementation(() => {
  return "Mock Login Method Called";
});

jest.doMock("api-name", () => () => {
  return {
    login: mockLogin,
  };
});

import { DataManager } from "../../core/dataManager";

describe("DataManager.setup_api", () => {
  it("should login to API with correct parameters", async () => {
    //Arrange
    let manager: DataManager = new DataManager();

    //Act
    const result = await manager.setup_api();

    //Assert
    expect(result).toEqual("Mock Login Method Called");
    expect(mockLogin).toHaveBeenCalledWith("[email protected]", "password");
  });
});

Again, this is really only relevant when using ts-jest, as using babel to transform your jest typescript tests WILL support the correct hoisting behavior. This is subject to change in the future, with updates to ts-jest, but the jest.doMock() workaround seems good enough for the time being.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top