我如何使用 vitest 对 axios.create 模拟进行单元测试?

ala*_*aza 5 typescript axios axios-mock-adapter vuejs3 vitest

我正在使用 typescript 在 vue 中学习单元测试,我想测试这个功能

\n
const getCLients =async (): Promise<Client[]> => {\n        const {data} = await clientsApi.get('/clients')\n        return data\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但由于clientsApi,我遇到了错误。我的客户端 api 是 aun axios 实例,如下所示:

\n
import axios from 'axios'\n\nconst clientsApi = axios.create({\n   baseURL:import.meta.env.VITE_API_URL\n})\nexport default clientsApi\n
Run Code Online (Sandbox Code Playgroud)\n

我的错误是这样的:

\n
\n

类型错误:无法读取未定义的属性(读取“get”)\n\xe2\x9d\xaf getCLients ../src/clients/composables/useClients.ts:14:41

\n
\n
\n

14| const {data} = 等待clientsApi.get('/clients')

\n
\n

在我的测试中,我完成了 axios 模拟:

\n
vi.mock('axios')\nconst mockedAxios = axios as jest.Mocked<typeof axios>;\n\nmockedAxios.get.mockResolvedValue({\n            data: mockClients,\n})\n
Run Code Online (Sandbox Code Playgroud)\n

我以为我必须模拟 axios.create 但我尝试了很多方法,但我总是遇到相同的打字错误。我需要你的帮助,你该如何解决这个问题?

\n

小智 1

不确定我是否走在正确的轨道上,因为它只对我有效。我有vi.mock('axios')并且已经有Error: spyOn could not find an object to spy uponenter code here。所以我确实这样做了vi.mock(the path to the instance ),而且vi.spyOn(the axios instance, 'get').mockResolvedValue就你的情况而言,可能是这样clientsApi