Mock fetch method

Hi there,

I am trying to implement unit tests with jest. And I am not able to mock function fetchfrom @forge/api.

Code:

# __mocks__/@forge/api.ts
import {resetAllWhenMocks, when} from "jest-when";

const mockFetch = jest.fn();

const getMockFetch = (): jest.Mock => {
    return mockFetch;
};

const fetch = async (requestUrl: string, init: RequestInit): Promise<APIResponse> => {
    return mockFetch(requestUrl, init);
};

const resetMocks = (): void => {
    resetAllWhenMocks();
    mockFetch.mockClear();
}

const setResponse = ( method: string,  isSuccessful: boolean, status: number): void=> {
    when(mockFetch)
        .calledWith( expect.objectContaining({method: method}))
        .mockReturnValue(new APIResponse(isSuccessful, status));
}

interface RequestInit {
    body?: any;
    headers?:any;
    method?: any;
}

class APIResponse {
    constructor(isSuccessful: boolean, status: number) {
        this.ok = isSuccessful;
        this.status = status;
    }
    ok: boolean;
    status: number;
    statusText: string;
    type: ResponseType;
    url: string;
}

export {mockFetch, fetch, resetMocks, setResponse, getMockFetch};
#test.ts
import {getMockFetch, resetMocks, setResponse} from "../../../__mocks__/@forge/api";
import {authenticated} from "../../api/SentinelAPI";

jest.mock("@forge/api");
jest.spyOn(global.console, "error").mockImplementation(() => {});

beforeEach(() =>{
    resetMocks();
});

test('Authentication is successful', async () => {
    setResponse( "GET", true, 200);
    await authenticated("API_KEY");

    const mock = getMockFetch().mock;
    expect(mock.calls.length).toBe(1);

});

Error:

TypeError: Cannot read properties of undefined (reading 'mock')

      13 |     await authenticated("API_KEY");
      14 |
    > 15 |     const mock = getMockFetch().mock;
         |                                ^
      16 |     expect(mock.calls.length).toBe(1);
      17 |
      18 | });

Looks like it does not return mockFetch method. How to mock fetch method properly?]

that seems quite strange. Ran it myself and it worked properly.

My best guess is if some other test or part of code is messing with mockFetch.

Is this your only test? If not could you isolate it so only this test is being run?

If the problem still appears you may be better off asking jest about this. I don’t believe this is to do with our api.