Search code examples
javascriptreactjsjestjsaxiosreact-hooks-testing-library

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


I am trying to test below function or in other words I am trying to write unit test cases of below function.But I am getting error _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];
};

here is my code https://codesandbox.io/s/awesome-jepsen-5os4e?file=/src/usetabData.test.js

I write unit test case like that

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();
  });
});

Solution

  • Code sandbox doesn't support manual mocks as far as I know. However, your __mock__ is placed in wrong directory structure. It should be a sibling of node_module.

    Having said that, easiest way is to use 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
      });
    });
    

    You can use history to assert: https://github.com/ctimmerm/axios-mock-adapter#history