How to set the data type of Axios mock using Jest TypeScript?

Sometimes, we want to set the data type of Axios mock using Jest TypeScript.

In this article, we’ll look at how to set the data type of Axios mock using Jest TypeScript.

How to set the data type of Axios mock using Jest TypeScript?

To set the data type of Axios mock using Jest TypeScript, we can use the jest.Mocked<typeof axios> type.

For instance, we write

import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

//...

mockedAxios.get.mockRejectedValue('error');
mockedAxios.get.mockResolvedValue({ data: {} });

to set the type of mockedAxios to jest.Mocked<typeof axios> with as.

We mock Axios with jest.mock('axios').

And then we can call mockedAxios.get.mockRejectedValue or mockedAxios.get.mockResolvedValue to set the mocked resolve or reject value of the promise returned by axios.get.

Conclusion

To set the data type of Axios mock using Jest TypeScript, we can use the jest.Mocked<typeof axios> type.