当想要用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错误:
Property 'mockReturnValueOnce' does not exist on type '(url: string, config?: AxiosRequestConfig | undefined) => AxiosPromise'.
axios.get
的typedef不包括mockReturnValueOnce
属性.我们可以通过将Typescript包装为Object(axios.get)
来强制将axios.get
视为对象文字,但是:
在维护类型安全的同时模拟函数的惯用方法是什么?