当想要用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视为对象文字,但是:

在维护类型安全的同时模拟函数的惯用方法是什么?

推荐答案

添加这行代码const mockedAxios = axios as jest.Mocked<typeof axios>.然后使用mockedAxios调用mockeReturnValues一次.

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);
});

Node.js相关问答推荐

需要关于基于角色授权的设计建议

如何在Mongoose中调用动态Collection ?

如何在Angular jest测试中调用Nodejs的垃圾收集? node v20的测试速度慢且内存泄漏

如何发送比特币BTC使用发送加密使用WIF密钥在 node ,js

如果我加入另一个公会且我的​​机器人已在其中,欢迎消息发送错误

TypeScript Eslint警告了一个AWS客户端构造函数(dynamodb),但没有警告另一个(s3)

如何调用同名的两个函数?

来自 child_process.exec 的错误没有这样的设备或地址,管道有帮助.为什么?

NestJS 共享模块的问题

try 运行迁移时的 Typeorm:缺少必需的参数:dataSource

Node js中向rest服务发送https请求的步骤

Nodejs-console.error vs util.debug

如何将使用 Gulp 的 node 部署到 heroku

如何使用 Puppeteer 从输入中删除现有文本?

所有的javascript回调都是异步的吗?如果不是,我怎么知道哪些是?

为什么我们要为 Angular 2.0 安装 Node.js?

如何从命令行在 Node.js 上运行 Jasmine 测试

如何使用 cookie 创建 HTTP 客户端请求?

如何判断MongoDB本机nodejs驱动程序中是否存在集合?

未找到 PM2 命令