开玩笑测试Axios的意义是什么

发布于 2025-02-11 10:53:33 字数 1167 浏览 1 评论 0原文

因此,我一直在阅读如何使用Jest测试Axios。例如,Robin Wieruch https://www.robinwieruch.de/axios.de/axios-jest/ < /a>。我不明白的是,在这些示例中,我们实际上有一个虚拟数据,我们希望API返回。但是,我可以将这些虚拟数据更改为真正的任何事情,并且测试仍然可以通过。那么重点是什么呢?

更新:添加文章中的代码。

import axios from 'axios';

import { fetchData } from './';

jest.mock('axios');

describe('fetchData', () => {
  it('fetches successfully data from an API', async () => {
    const data = {
      data: {
        hits: [
          {
            objectID: '1',
            title: 'a',
          },
          {
            objectID: '2',
            title: 'b',
          },
        ],
      },
    };

    axios.get.mockImplementationOnce(() => Promise.resolve(data));
    await expect(fetchData('react')).resolves.toEqual(data);
  });

  it('fetches erroneously data from an API', async () => {
    const errorMessage = 'Network Error';

    axios.get.mockImplementationOnce(() =>
      Promise.reject(new Error(errorMessage)),
    );

    await expect(fetchData('react')).rejects.toThrow(errorMessage);

  });
});

So I've been reading on how to test axios in react using JEST. For instance, this article by Robin Wieruch https://www.robinwieruch.de/axios-jest/. The thing I don't understand is that in these examples, we actually have dummy data that we expect the API to return. However, I could change that dummy data to be anything really, and the test would still pass. So what is the point?

Update: Adding code from the article.

import axios from 'axios';

import { fetchData } from './';

jest.mock('axios');

describe('fetchData', () => {
  it('fetches successfully data from an API', async () => {
    const data = {
      data: {
        hits: [
          {
            objectID: '1',
            title: 'a',
          },
          {
            objectID: '2',
            title: 'b',
          },
        ],
      },
    };

    axios.get.mockImplementationOnce(() => Promise.resolve(data));
    await expect(fetchData('react')).resolves.toEqual(data);
  });

  it('fetches erroneously data from an API', async () => {
    const errorMessage = 'Network Error';

    axios.get.mockImplementationOnce(() =>
      Promise.reject(new Error(errorMessage)),
    );

    await expect(fetchData('react')).rejects.toThrow(errorMessage);

  });
});

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文