React / Jest-是否有一种方法可以等待模拟解决后再渲染

时间:2020-04-29 20:48:40

标签: javascript reactjs jestjs

在我的react组件中,默认情况下我将load设置为true,然后将fetch的fetch设置为false。 当我返回自己的jsx代码时,我有一个类似{! loading &&的检查程序可以正常工作,但是在我的测试中,提取操作已被模拟并通过调用,但是它首先调用了渲染,因此不会渲染组件。

test('App component renders and contains prop given to it', async () => {
  jest.spyOn(window, 'fetch').mockResolvedValue({
    json: jest.fn().mockResolvedValue({ value: 'test' }) as Partial<Response>,
  } as Response);

  await act(async () => {
    const testProp = 'my test';

    const { container, getByText } = render(<App testProp={testProp} />);

    const testPropElement = getByText(testProp);
    console.log('test2');

    expect(testPropElement).toBeInTheDocument();
  });
});

获取内容类似于:

fetch(`/api/url`)
      .then((response) => response.json())
      .then((data) => {
        console.log('test1');
        setLoading(false);
      });

当我在控制台日志中查看事物的顺序时,肯定要进行模拟操作,然后在“ test2”之后显示“ test1”。

有人有什么想法吗? 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

之所以观察到这一点,是因为您的获取模拟(以及获取本身)返回Promise,您在测试中没有解决该问题,但是Jest在完成后会自动为您解决它。您想在期望之初解决它,以便可以进行then回调,更改状态并重新渲染组件。

反应测试库(我看到您正在使用)为此场合提供实用程序功能:waitFor。只需等待一段时间,您的承诺就会解决,元素就会出现。

或者,您可以使用findByText,您可以使用await(基本上只是promisified函数的getBy*版本),它的作用也与上述相同。 / p>