i am learning unit testing in vue with typescript and i want to test this function
const getCLients =async (): Promise<Client[]> => {
const {data} = await clientsApi.get('/clients')
return data
}
But i got an error due to the clientsApi. My clients api is aun axios instance and looks like this:
import axios from 'axios'
const clientsApi = axios.create({
baseURL:import.meta.env.VITE_API_URL
})
export default clientsApi
my error is this:
TypeError: Cannot read properties of undefined (reading 'get') ❯ getCLients ../src/clients/composables/useClients.ts:14:41
14| const {data} = await clientsApi.get('/clients')
In my tests i have done the axios mock:
vi.mock('axios')
const mockedAxios = axios as jest.Mocked<typeof axios>;
mockedAxios.get.mockResolvedValue({
data: mockClients,
})
I suposed that i had to make a mock of the axios.create but i have tried with a lot of ways but i always got the same typoe error. I need your help, how could you solve this?
If, for instance, you're using
axios.create()
in your codebase to generate anAxiosInstance
, you can mock this functionality as follows in your Vitest test file:Initially, we set up the
mocks
object that includes theget
andpost
functions we want to mock. Usingvi.hoisted()
, we ensure these mocked functions are hoisted (i.e., moved to the top of the scope), allowing us to reference them within ourvi.mock()
function.Then, we mock the entire
axios
module usingvi.mock()
. In order to maintain the existing functionality that we don't intend to mock, we employimportActual
to import the realaxios
module. We then specify the parts we wish to mock, namely thecreate
function and theget
/post
functions.With these mocks in place, we can now spy on our mocked
get
andpost
methods. Here's an example of how to do it:In the test case, we mock a resolved value for our
get
method and call the function we want to test (clientsApi.getCLients()
in this case). We then check whether our mockedget
function has been called usingexpect().toHaveBeenCalled()
.This setup provides a controlled environment to test the interactions with the axios library in our code.