0

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();
  });
});
user944513
  • 12,247
  • 49
  • 168
  • 318

1 Answers1

0

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

Karthik R
  • 5,523
  • 2
  • 18
  • 30
  • could you please I tried different way to check `setState` is called or not https://codesandbox.io/s/sweet-meadow-9l41z?file=/src/useTabData.test.js – user944513 Jul 25 '20 at 12:21
  • sorry. This diverges from question or issue you have. create a diff issue. Your current code has moxios but there seems to be other errors in mocking and usage of `React.useState` which is incorrect. You can start from what I have posted above and try from there. – Karthik R Jul 25 '20 at 12:26