Typescript和Jest:避免在模拟函数上键入错误

duncanhall:

当想用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TypeScript:键入模拟函数

如何使用 TypeScript 和 Jest 模拟深度嵌套的函数

如何在 TypeScript 中正确键入“省略”函数以避免错误消息?

如何使用 Jest 和 Typescript 测试“返回错误的函数”?

在 Jest 和 Typescript 中模拟 addEventHandler

使用 Typescript 和 Jest 的简单获取模拟

使用 useReducer 和 Context 与 Typescript 键入错误

如何修复递归化简函数上的Typescript错误

如何使用Jest在TypeScript中模拟导入的函数?

模拟使用Typescript和Jest进行测试的类

使用正确的类型用Jest和Typescript模拟Express请求

如何避免每个函数上的bind(this)?

用Jest在递归函数中模拟Promise和Timer

使用 jest 和 superagent 进行测试时如何模拟函数

我不明白我在def函数上键入的错误,但是在Python上都正确吗?

memcpy() 函数上的分段错误

接受函数上的Winsock错误

映射类型和泛型函数键入错误

TypeScript-Jest的mockResolvedValueOnce方法中的Entity上的“无法分配给永不键入”错误

打字稿在正确键入的参数上引发错误

Reduce函数上的几个Typescript(不能分配给类型的参数)错误

如何避免TypeScript mixins出现“无法解析的函数”错误?

无法在 Jest 中模拟函数

在Jest中模拟函数调用

难以理解模拟的 Jest 函数

在TypeScript中键入mapShape函数

TypeScript - 键入函数的最佳方法?

TypeScript如何在数组的Reduce函数上设置累积值和initialValue的类型

当我尝试在异步函数上使用toThrow()时,Jest Test记录了一个错误(但仍通过测试)