Jest mocking implementation of a function within the same test file

Viewed 17

I am attempting to write unit tests for a file containing several util functions. They are all default exported.

However, one of my functions myGreenFunction actually calls another util function in that file as part of its processes, myRedFunction.

In other tests in this file, when I have needed to call an external function, I have mocked it using mockImplementation as I don't care about the response, but rather that it was called with the expected parameters.

However, whilst testing myGreenFunction and following my same pattern of mocking the implementation of the called myRedFunction, I get an error. I believe this error may be because a function not mocked using jest.mock("./file") may not be able to be mocked using .mockImplementation?

How can I structure my mocks in this case when the function I want to mock is also present in the test file?

Unit tests:

import { myGreenFunction, myRedFunction } from "./myUtils";

describe("Testing utils", () => {
  describe("Testing myGreenFunction", () => {
    beforeEach(() => {
      myRedFunction.mockImplementation(() => { "foo": "bar" } ); // here lies the issue
    });

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

    it("should call myRedFunction with the expected params", () => {
      myGreenFunction();

      expect(myRedFunction).toHaveBeenCalledWith("foo");
    });
  });
});

SUT:

export default function myGreenFunction(param) {
  //....
  myRedFunction(param);
}

export default function myRedFunction(param) {
  // do stuff
  return { "foo": param }
}

In the above example you can hopefully see where myRedFunction.mockImplementation is set. This is the error that occurs on the test run:

TypeError: _myUtils.myRedFunction.mockImplementation is not a function

This pattern seemingly works fine if I abstracted myRedFunction away to another file and then mocked it in, but I don't want to do that.

Is there any way to get this pattern working?

0 Answers
Related