使用 jest 打字稿的 Axios 模拟类型 [英] Type of Axios mock using jest typescript

查看:20
本文介绍了使用 jest 打字稿的 Axios 模拟类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个类中有以下方法:

I have the following method in a class:

import axios from 'axios'

public async getData() {
   const resp = await axios.get(Endpoints.DATA.URL)
   return resp.data
}

然后我正在尝试设置一个执行此操作的 Jest 测试:

Then I am trying to set up a Jest test that does this:

jest.mock('axios')

it('make api call to get data', () => {
   component.getData()
   expect(axios.get).toHaveBeenCalledWith(Endpoints.DATA.URL)
})

问题是因为我没有模拟返回值,所以它给 resp.data 一个错误,因为我在 null 上调用 dataundefined 对象.我花了至少 2 个小时尝试各种方法来让它工作,但我找不到一种方法可以用一些返回值模拟 axios.get.

The problem is that because I am not mocking the return value, then it gives an error for resp.data because I'm calling data on null or undefined object. I spent at least 2 hours trying various ways to get this working but I can't find a way such that I can mock axios.get with some return value.

Jest 的文档使用 JavaScript,所以他们给出了这个例子 axios.get.mockResolvedValue(resp) 但我无法调用 mockResolvedValue 因为该方法在 TypeScript 中的 axios.get 上不存在.

Jest's documentation uses JavaScript so they give this example axios.get.mockResolvedValue(resp) but I can't call mockResolvedValue because that method does not exist on axios.get in TypeScript.

此外,如果您知道除 Jest 之外的其他优秀的 React 测试库,可以轻松地为 TypeScript 完成这些工作,请随时分享.

Also, if you know other good testing library for React other than Jest that does this stuff easily for TypeScript, feel free to share.

推荐答案

在文件开头:

import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

现在你可以像往常一样使用它:

Now you can use it as usual mock:

mockedAxios.get.mockRejectedValue('Network error: Something went wrong');
mockedAxios.get.mockResolvedValue({ data: {} });

这篇关于使用 jest 打字稿的 Axios 模拟类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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