【问题标题】:how to get check setState function callled or not in react js using hooks?如何使用钩子在 React js 中调用或不调用 setState 函数?
【发布时间】:2020-11-15 04:34:00
【问题描述】:

我正在尝试测试custom hook。我想知道setState 函数是否触发。 这是我的自定义钩子

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

现在我正在尝试测试这个custom 钩子。我想知道setState函数是否触发。

我试过这样

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

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs react-hooks


    【解决方案1】:

    你不应该嘲笑 React 内部。这是不正确的。无论哪种方式,由于闭包,此代码在模拟中无效。即使它有效,如果你在模拟真正的实现,测试也没有意义,不是吗? :)

    我建议您尝试了解 react 钩子在您的代码中的作用。

    您的自定义钩子中有一个状态:

    const [state, setState] = React.useState([]);
    .
    .
    
    return [state]; //you are returning the state as ARRAY
    

    @testing-library/react-hooks 允许您调试并获取钩子当前结果的值。

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

    我会在这里停下来,让您学习和调试。

    【讨论】:

    • 那么要测试什么??
    • 抱歉回复晚了……!!你能告诉我我将在这个函数中测试什么
    • 我已经给出了答案!您可能需要了解一些基础知识才能加快速度。
    • 好的,谢谢,但是我可以在承诺解决后检查更新的状态值吗?
    • 承诺后应该有array of object而不是空白数组
    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 2016-03-10
    • 2021-12-12
    • 2020-08-30
    • 1970-01-01
    • 2021-02-14
    • 2020-05-29
    相关资源
    最近更新 更多