“反应检测到挂钩的顺序发生了变化”

时间:2020-06-19 18:19:40

标签: reactjs jestjs react-hooks

我在编写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");
  });
});

0 个答案:

没有答案