当想要用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相关问答推荐

利用Gemini:通过Vertex AI还是通过Google/generative-ai?

Stripe webhook无法访问Express请求原始正文

如何在ejs模板中使用循环显示多个结果?

JsonwebToken过期后如何注销和清除cookie?

当 Got 包因错误 JSON 崩溃时如何获取响应文本?

在对象数组中的数组中嵌套 $lookup - Mongodb

TypeError:在使用 Jest、Supertest、Express、Typescript 进行测试时无法读取未定义的属性(读取listen)

为什么当我try req.logout() 时出现此错误?

获取数组的至少一个元素包含子字符串的文档

Sharp JS 依赖关系 destruct 了 Elastic Beanstalk 上的 Express Server

如何在 TypeScript 中输出 Hackerrank 二叉树问题?

cURL 和 shell 任务

Mongoose:查找、修改、保存

如何在 node 中找到引用站点 URL?

node.js 模块和函数中this的含义

在单独的模块中定义 Mongoose 模型

安装Node.js 安装n 安装Node.js?

Node.js:如何附加到正在运行的进程并使用控制台调试服务器?

node.js 异步库

如何阻止 babel 将this转换为undefined(并插入use strict)