简体   繁体   中英

how to get check setState function callled or not in react js using hooks?

I am trying to test custom hook . I want to know is setState function fire or not. here is my custom hook

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

now I am trying to test this custom hook. I want to know is setState function fire or not.

I tried like this

import moxios from "moxios";
import React from "react";
import { act, renderHook, cleanup } from "@testing-library/react-hooks";

import useTabData from "./useTabData";
describe("use tab data", () => {
  beforeEach(() => {
    moxios.install();
  });
  afterEach(() => {
    moxios.uninstall();
  });

  describe("non-error response", () => {
    // create mocks for callback arg
    const data = [
      {
        name: "hello"
      }
    ];
    let mockSetCurrentGuess = jest.fn();
    beforeEach(async () => {
      moxios.wait(() => {
        const request = moxios.requests.mostRecent();
        request.respondWith({
          status: 200,
          response: data
        });
      });
    });

    test("calls setState with data", async () => {
      React.useState = jest.fn(() => ["", mockSetCurrentGuess]);
      const { result, waitForNextUpdate } = renderHook(() => useTabData());
      console.log(result);
      //expect(mockSetCurrentGuess).toHaveBeenCalledWith(data);
    });
  });
});

You should not mock the React internals. This is incorrect. Either ways, this code has no effect in mocking due to closures. Even if it worked, no point in testing if you are mocking the real implementation, isn't it? :)

I would recommend to try to get grasp of what react hook is doing in your code.

You have a state in your custom hook:

const [state, setState] = React.useState([]);
.
.

return [state]; //you are returning the state as ARRAY

@testing-library/react-hooks allows you to debug and get value of current outcome of hook.

const { result, waitForNextUpdate } = renderHook(() => useTabData());
const [foo] = result.current; // the array you returned in hook
expect(foo).toEqual('bar'); //example assertion

I would stop here and allow you to learn and debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM