0

我正在尝试测试以下功能,或者换句话说,我正在尝试编写以下功能的单元测试用例。但是我遇到了错误_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();
  });
});
4

1 回答 1

0

据我所知,代码沙箱不支持手动模拟。但是,您__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

于 2020-07-25T12:11:26.110 回答