如何检查axios get函数在react js中是否被调用?

how to check axios get function called or not in react js?

我正在尝试测试以下功能,或者换句话说,我正在尝试编写以下单元测试用例 function.But 我收到错误 _axios.default.get.mockResolvedValueOnce is not a function

import React from "react";
import axios from "axios";
export default () => {
  const [state, setState] = React.useState([]);

  const fetchData = async () => {
    const res = await axios.get("https://5os4e.csb.app/data.json");
    setState(res.data);
  };

  React.useEffect(() => {
    (async () => {
      await fetchData();
    })();
  }, []);

  return [state];
};

这是我的代码 https://codesandbox.io/s/awesome-jepsen-5os4e?file=/src/usetabData.test.js

我就是这样写单元测试用例的

import useTabData from "./useTabData";
import { act, renderHook, cleanup } from "@testing-library/react-hooks";
import mockAxios from "axios";
describe("use tab data", () => {
  afterEach(cleanup);
  it("fetch tab data", async () => {
    mockAxios.get.mockResolvedValueOnce({
      data: {
        name: "hello"
      }
    });
    await act(async () => renderHook(() => useTabData()));
    expect(mockAxios.get).toHaveBeenCalled();
  });
});

据我所知,代码沙箱不支持手动模拟。 但是,您的 __mock__ 放置在错误的目录结构中。它应该是 node_module.

的兄弟姐妹

话虽如此,最简单的方法是使用 https://github.com/ctimmerm/axios-mock-adapter

import useTabData from "./useTabData";
import { act, renderHook, cleanup } from "@testing-library/react-hooks";
import axios from "axios";
import MockAxiosAdapter from "axios-mock-adapter";

const mockAxios = new MockAxiosAdapter(axios);
afterEach(() => {
    cleanup();// this is not needed . its done by testing library after each.
    mockAxios.reset();
  });
describe("use tab data", () => {
  it("fetch tab data", async () => {
    mockAxios.onGet(200, { data: { test: "123" } }); // response code and object.
    const { result, waitForNextUpdate } = renderHook(() => useTabData());
    const [value] = result.current;
    // assert value
    // assert the axios call by using history object
  });
});

您可以使用历史来断言:https://github.com/ctimmerm/axios-mock-adapter#history