简体   繁体   English

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

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

In my react component I have loading set to true by default, and then a fetch which on the return sets loading to false.在我的反应组件中,默认情况下我将加载设置为 true,然后在返回时将加载设置为 false 的 fetch。 When I return my jsx code I have a check like {! loading &&当我返回我的 jsx 代码时,我有一个像{! loading && {! loading && which works, but in my test, the fetch is being mocked and called through but it calls the render first so it doens't render the components. {! 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();
  });
});

The fetch looks something like:获取看起来像:

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

When I console log to see the order of things, it is definitely going through with the mockResolvedValue and showing 'test1' after 'test2'.当我通过控制台查看事情的顺序时,它肯定会通过 mockResolvedValue 并在“test2”之后显示“test1”。

Anyone got any ideas?有人有什么想法吗? thanks for the help.谢谢您的帮助。

You are observing this because your fetch mock (and fetch itself) returns Promise which you are not resolving in your test, but rather Jest automatically resolves it for you after it's finished.您正在观察这一点,因为您的 fetch 模拟(和 fetch 本身)返回 Promise ,您没有在测试中解决它,而是 Jest 在完成后自动为您解决它。 You want to resolve it before your expect so it can go to then callback, change a state and do the re-render of a component.您想在您期望之前解决它,以便它可以 go then回调,更改 state 并重新渲染组件。

React-testing-library (which I see you are using) is providing utility function for this occasion: waitFor . React-testing-library(我看到你正在使用)为此提供实用程序 function: waitFor It would just wait some time for your promise to resolve and element to appear.它只会等待您的 promise 解决并出现元素。

Alternatively you can use findByText , which you can await (basically just a promisified version of getBy* functions) and it would also do the same as above.或者,您可以使用findByText ,您可以await它(基本上只是promisified getBy*函数的承诺版本),它也可以执行与上述相同的操作。

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

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