当想用Jest模拟外部模块时,我们可以使用该jest.mock()方法来自动模拟模块上的功能。
jest.mock()
然后,我们可以根据需要在模拟模块上操纵和询问模拟函数。
例如,考虑以下模拟axios模块的人为示例:
import myModuleThatCallsAxios from '../myModule'; import axios from 'axios'; jest.mock('axios'); it('Calls the GET method as expected', async () => { const expectedResult: string = 'result'; axios.get.mockReturnValueOnce({ data: expectedResult }); const result = await myModuleThatCallsAxios.makeGetRequest(); expect(axios.get).toHaveBeenCalled(); expect(result).toBe(expectedResult); });
上面的代码在Jest中可以正常运行,但会引发Typescript错误:
类型’(url:string,config ?: AxiosRequestConfig | undefined)=> AxiosPromise’不存在属性’mockReturnValueOnce’。
axios.get正确的typedef 不包含mockReturnValueOnce属性。我们可以axios.get通过将TypeScript 包装为来强制将Typescript 视为Object文字Object(axios.get),但是:
axios.get
mockReturnValueOnce
Object(axios.get)
在保持类型安全的同时模仿函数的惯用方式是什么?
添加此行代码const mockedAxios = axios as jest.Mocked<typeof axios>。然后使用mockedAxios调用mockReturnValueOnce。使用您的代码,应该像这样完成:
const mockedAxios = axios as jest.Mocked<typeof axios>
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); });