繁体   English   中英

React/Jest - 有没有办法在渲染之前等待模拟解决

[英]React/Jest - Is there a way to wait for a mock to resolve before rendeing

在我的反应组件中,默认情况下我将加载设置为 true,然后在返回时将加载设置为 false 的 fetch。 当我返回我的 jsx 代码时,我有一个像{! loading && {! loading &&可以工作,但在我的测试中, fetch 被模拟并通过调用,但它首先调用渲染,因此它不会渲染组件。

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

当我通过控制台查看事情的顺序时,它肯定会通过 mockResolvedValue 并在“test2”之后显示“test1”。

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

您正在观察这一点,因为您的 fetch 模拟(和 fetch 本身)返回 Promise ,您没有在测试中解决它,而是 Jest 在完成后自动为您解决它。 您想在您期望之前解决它,以便它可以 go then回调,更改 state 并重新渲染组件。

React-testing-library(我看到你正在使用)为此提供实用程序 function: waitFor 它只会等待您的 promise 解决并出现元素。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM