Typescript和Jest:避免在模拟函数上出现类型错误 [英] Typescript and Jest: Avoiding type errors on mocked functions

查看:190
本文介绍了Typescript和Jest:避免在模拟函数上出现类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当想用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不存在属性'mockReturnValueOnce' 字符串,配置?:AxiosRequestConfig |未定义)=> AxiosPromise'.

Property 'mockReturnValueOnce' does not exist on type '(url: string, config?: AxiosRequestConfig | undefined) => AxiosPromise'.

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:避免在模拟函数上出现类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆