Typescript 和 Jest:避免模拟函数上的类型错误 [英] Typescript and Jest: Avoiding type errors on mocked functions
问题描述
当想用 Jest 模拟外部模块时,我们可以使用 jest.mock()
方法在模块上自动模拟函数.
When wanting to mock external modules with Jest, we can use the jest.mock()
method to auto-mock functions on a module.
然后我们可以随意操作和询问模拟模块上的模拟函数.
We can then manipulate and interrogate the mocked functions on our mocked module as we wish.
例如,考虑以下模拟 axios 模块的人为示例:
For example, consider the following contrived example for mocking the axios module:
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 错误:
The above will run fine in Jest but will throw a Typescript error:
类型 '(url:字符串,配置?:AxiosRequestConfig |undefined) => AxiosPromise'.
Property 'mockReturnValueOnce' does not exist on type '(url: string, config?: AxiosRequestConfig | undefined) => AxiosPromise'.
axios.get
的 typedef 正确地不包含 mockReturnValueOnce
属性.我们可以通过将 axios.get
包装为 Object(axios.get)
来强制 Typescript 将其视为 Object 字面量,但是:
The typedef for axios.get
rightly doesn't include a mockReturnValueOnce
property. We can force Typescript to treat axios.get
as an Object literal by wrapping it as Object(axios.get)
, but:
在保持类型安全的同时模拟函数的惯用方法是什么?
What is the idiomatic way to mock functions while maintaining type safety?
推荐答案
添加这行代码const mockedAxios = axios as jest.Mocked
.然后使用 mockedAxios 调用 mockReturnValueOnce.使用您的代码,应该这样做:
Add this line of code const mockedAxios = axios as jest.Mocked<typeof axios>
. And then use the mockedAxios to call the mockReturnValueOnce.
With your code, should be done like this:
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);
});
这篇关于Typescript 和 Jest:避免模拟函数上的类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!