Cannot Get Jest + Typescript + Axios Test
In start of file:
import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
Now you can use it as usual mock:
mockedAxios.get.mockRejectedValue('Network error: Something went wrong');
mockedAxios.get.mockResolvedValue({ data: {} });
If you want to use jest.mock
with "no-any"
try this:
import axios, { AxiosStatic } from 'axios'
interface AxiosMock extends AxiosStatic {
mockResolvedValue: Function
mockRejectedValue: Function
}
jest.mock('axios')
const mockAxios = axios as AxiosMock
it('make api call to get data', () => {
// call this first
mockAxios.mockResolvedValue(yourValue)
component.getData()
expect(mockAxios.get).toHaveBeenCalledWith(Endpoints.DATA.URL)
})
but I can't call mockResolvedValue because that method does not exist on axios.get in TypeScript
You can use an assertion:
(axios.get as any).mockResolvedValue(resp)