React jest 测试未达到 api 覆盖率

发布于 2025-01-13 01:09:22 字数 979 浏览 3 评论 0原文

我在某些组件中调用了这个 api 代码。

const Api: IApi = {
  delete: (url: string): Promise<any> => {
    return axios.delete(url);
  },
  get: (url: string): Promise<any>  => {
    return axios.get(url)
  },
  post: (url: string, payload: IContact): Promise<any> => {
    return axios.post(url, JSON.stringify(payload))
  },
  put: (url: string, payload: IContact): Promise<any>  => {
    return axios.put(url, JSON.stringify(payload))
  },
}

export { Api }

除 API 外,所有使用此 api 的组件均已测试为 100% 覆盖率。 输入图片description here

没有覆盖的文件是接口(类型)文件。

我现在面临的问题是尝试测试 API,使其达到 100% 的覆盖率,但所有场景都失败了。尽管所有其他方法都已成功模拟,但仅覆盖了 get 方法。

报道如此表现到底是怎么回事?

输入图片此处描述

如何实现此覆盖范围?

I have this api code called in some components.

const Api: IApi = {
  delete: (url: string): Promise<any> => {
    return axios.delete(url);
  },
  get: (url: string): Promise<any>  => {
    return axios.get(url)
  },
  post: (url: string, payload: IContact): Promise<any> => {
    return axios.post(url, JSON.stringify(payload))
  },
  put: (url: string, payload: IContact): Promise<any>  => {
    return axios.put(url, JSON.stringify(payload))
  },
}

export { Api }

All the components that use this api have been tested to 100% coverage except the API.
enter image description here

The files without coverage are interface (types) files.

The issue I am facing now is to try and test the API so it hits 100% coverage but all scenarios have failed. The get method only is covered even though all the other methods have been successfully mocked.

What is really going on here for the coverage to behave like this?

enter image description here

How can this coverage be achieved?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Oo萌小芽oO 2025-01-20 01:09:22

您应该模拟 axios 库,调用 deletepost & put 方法到您的测试中并确保正确调用模拟。

像这样的事情:

import axios from 'axios';
import { Api } from './users';

jest.mock('axios');

describe('Api', function() {
  it('should call delete correctly', () => {
    const url = 'https://stackoverflow.com/';

    Api.delete(url);

    expect(axios.delete).toHaveBeenCalledWith(url);
  });
});

You should mock the axios library, call the delete, post & put methods in your tests and make sure the mocks are correctly called.

Something like this:

import axios from 'axios';
import { Api } from './users';

jest.mock('axios');

describe('Api', function() {
  it('should call delete correctly', () => {
    const url = 'https://stackoverflow.com/';

    Api.delete(url);

    expect(axios.delete).toHaveBeenCalledWith(url);
  });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文