当想用Jest模拟外部模块时,我们可以使用该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)
,但是:
在保持类型安全的同时模仿函数的惯用方式是什么?
添加此行代码const mockedAxios = axios as jest.Mocked<typeof axios>
。然后使用mockedAxios调用mockReturnValueOnce。使用您的代码,应像这样完成:
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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句