To avoid type errors on mocked functions with TypeScript and Jest, we use the typeof
operator.
For instance, we write
import myModuleThatCallsAxios from "../myModule";
import axios from "axios";
jest.mock("axios");
const mockedAxios = axios as jest.Mocked<typeof axios>;
it("Calls the GET method as expected", async () => {
const expectedResult: string = "result";
mockedAxios.get.mockReturnValueOnce({ data: expectedResult });
const result = await myModuleThatCallsAxios.makeGetRequest();
expect(mockedAxios.get).toHaveBeenCalled();
expect(result).toBe(expectedResult);
});
to cast the type of mockedAxios
and axios
to jest.Mocked<typeof axios>
.
jest.Mocked
is the generic type for mocked objects.
typeof axios
gets the type of the axios
object automatically.