React Jest 错误:重新渲染次数过多。 React 限制渲染数量以防止无限

问题描述 投票:0回答:1

我不明白为什么会出现错误“重新渲染次数过多。React 限制渲染次数以防止无限循环。”当我运行测试时,这就是我提出请求的地方:

// usePokemon.js

export const usePokemon = (pokemonName) => {
  const [pokemon, setPokemon] = useState(null);
  const [error, setError] = useState(null);
  const [isLoading, SetIsLoading] = useState(true);

  useEffect(() => {
    async function fetchPokemon() {
      SetIsLoading(true);
      try {
        let namePokemon = pokemonName.toLocaleLowerCase();
        const response = await fetch(
          `https://pokeapi.co/api/v2/pokemon/${namePokemon}`
        );
        const json = await response.json();
        setPokemon(json);
      } catch (err) {
        setError(err);
      }
      SetIsLoading(false);
    }
    fetchPokemon();
  }, [pokemonName]);

  return { pokemon, error, isLoading };
};

这是我的钩子测试:

//usePokemon.test.js

import { act, renderHook } from "@testing-library/react-hooks";
import { usePokemon } from "./usePokemon";

const getControlledPromise = () => {
  let deferred;
  const promise = new Promise((resolve, reject) => {
    deferred = { resolve, reject };
  });
  return { deferred, promise };
};

describe("Success test", () => {

    test("handles loading state correctly", async () => {
      const { deferred, promise } = getControlledPromise();
  
      global.fetch = jest.fn(() => promise);
  
      const { result, waitForNextUpdate } = renderHook(usePokemon);
  
      expect(result.current.isLoading).toBe(true);
      deferred.resolve();
  
      await waitForNextUpdate();
      expect(result.current.isLoading).toBe(false);
    });
});

Too many re-renders. React limits the number of renders to prevent an infinite loop.

  31 |       global.fetch = jest.fn(() => promise);
  32 |   
> 33 |       const { result, waitForNextUpdate } = renderHook(usePokemon);
     |                                             ^
javascript jestjs hook use-effect
1个回答
0
投票

我会监视负责发出组件中使用的请求的方法:

组件中的示例:

const { value, isFetching, params } = ExampleModel.methodName({
 startTime,
 endTime,
 someId
})

测试示例:

jest.spyOn(ExampleModel.methodName).mockReturnValue({
 isFetching: false,
 params: undefined,
 value: []
})
© www.soinside.com 2019 - 2024. All rights reserved.