首页 > 解决方案 > “React 检测到 Hook 的顺序发生了变化”

问题描述

我在为 Auth 组件编写测试时遇到了这个问题。不确定是我编写测试的方式有问题还是应用程序本身有问题。下面是错误。

         Previous render            Next render
         ------------------------------------------------------
      1. useState                   useState
      2. undefined                  useEffect

我在失败的测试中看到了这条消息。"比上一次渲染时渲染了更多的钩子。 "

当我在 useEffect 上添加控制台语句时,我看到它只被调用了一次。

下面是我的 Auth 组件。

const Auth: React.FC<Props> = (props) => {
 const state = useConsoleState();
 const [problemType, setProblemType] = React.useState<ProblemTypeEnum>("TECH");
React.useEffect(() => {
    switch (props.supportType) {
      case "limit":
        setProblemType("LIMIT");
        break;
      case "account":
        setProblemType("ACCOUNT");
        break;
      default:
        setProblemType("TECH");
        break;
    }
  }, [props.supportType]);
};
const userId = getUserOcid(state.userProfile);
const cimsUserValidationResult = authApiCalls.callCims(!props.csi, props.csi, userId, problemType, state.homeRegionName);

和我的测试

describe("Auth tests", () => {
  beforeEach(() => {
   const useEffect = jest.spyOn(React, "useEffect");
   useEffect.mockImplementationOnce(f => f());
   authApiCalls.callCims = jest.fn().mockReturnValue({
      loading: false,
      response: {
        response: {
          ok: true,
        },
      },
    } as QueryResult<ValidationResponse>);
  });
  const runProblemTypeTest = (url: string, supportType: SupportType) => {
    window = Object.create(window);
    Object.defineProperty(window, "location", {
      value: {
        href: url,
      },
      writable: true
    });
    mount(
      <Auth supportType=. {supportType}>
        <div>TestChild</div>
      </Authorization>
    );
    expect(authApiCalls.callCims).toHaveBeenCalledWith(
      false,
      "1234",
      "test",
      supportType,
      "homeRegion"
    );
  };
  it("check problem type passed to validate when problem type absent in the url", () => {
    runProblemTypeTest("http://www.test.com", "tech");
  });
});

标签: reactjsjestjsreact-hooks

解决方案


推荐阅读