问题描述
当想用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:
axios.get
的typedef正确不包含mockReturnValueOnce
属性.通过将axios.get
包装为Object(axios.get)
,我们可以强制Typescript将axios.get
视为对象文字,但是:
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<typeof axios>
.然后使用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:避免在模拟函数上出现类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!