0

I am trying to mock a method used by the class I'm testing. The method is located in the same file as the class I'm testing.

The tested file:

export function trackErrors() {
    console.log("This SHOULD NOT BE SEEN ON tests");
    // Currently this console log is visible hwne running tests
}

// Component that is tested 
export const form = () => {
    return <FormComponent callback={trackErrors} />
}

The test itself:

With mock

The jest.mock() is the first thing to happen, before the import.

jest.mock('./testedFile', () => {
    const actualModule = jest.requireActual('./testedFile')

    return new Proxy(actualModule, {
        get: (target, property) => {
            switch (property) {
                case 'trackErrors': {
                    return jest.fn()
                }
                default: {
                    return target[property]
                }
            }
        },
    })
})

import * as SModule from "./testedFile";

it.only("Calls trackErrors", async () => {
      const { getByTestId } = <SModule.form />;

      await typeEmail(getByTestId, "abcd");

      await waitFor(() => {
        expect(SModule.trackErrors).toHaveBeenCalledTimes(1);
      });
});

This does not work. When printing SModule.trackErrors, I can see the mocked function being put out. But when the test is executed, the test fails with 0 calls and I see this console.log This SHOULD NOT BE SEEN ON tests. That means that the method is mocked good inside the test, but when rendering the component it continues to call the prexistent method (the one not modked).

I've also tried the spyOn approach, but the outcome is exactly the same.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Chayemor
  • 3,577
  • 4
  • 31
  • 54

0 Answers0