jest.spyOn() on factory function of jest.mock("path", factory function)

Viewed 165

I am trying to spyOn a mocked factory function named getObject. I am doing it like this:

import Storage from "/path/"
const fs1 = new Storage("ffffff");
const fs = mocked(fs1);

jest.mock("path to library", () => {
  return {
    CAStorage: function () {
      return {
        getObject: async (
          _baseDirName: string,
          _fileName?: string
        ): Promise<Buffer> => {
          return Buffer.from(
            `some string`
          );
        },
      };
    },
  };
});

the spyOn code

describe("", () => {
  test("", async () => {
    let readFileSpy = jest.spyOn(fs, "getObject");
    expect(readFileSpy).toBeCalledTimes(1);
  });
});

The error I am getting is: Expected number of calls: 1 Received number of calls: 0

even though the function have been called once.

Thanks for the help!

1 Answers

Take a look at this blog post

TL;DR

You should set the prototype of the mocked library / module. e.g

import { ClassA } from "some/lib";

describe("description", () => {
  test("test description", () => {
    ClassA.prototype.functionToMock = jest.fn().mockImplementationOnce(() => {
      // your implementation here
    })
  })
})
Related