为什么与fetch api一起使用时,反应钩会抛出act错误?

Ade*_*uyi 7 reactjs react-testing-library react-hooks

Warning: An update to App inside a test was not wrapped in act(...).每当我提出API请求并更新状态时,我都会进入测试套件。

我正在使用反应测试库。我也尝试使用ReactDOM测试工具,得到了相同的结果。我尝试的另一件事是将容器包装在中act,仍然得到相同的结果。

请注意:我的应用程序正常运行,并且我的测试通过了。我只需要知道我在做错什么,或者是否是react-dom程序包中的错误使该错误出现。模拟控制台错误并将其静音是很不好的。

global.fetch = require('jest-fetch-mock');

it('should clear select content item', async () => {
    fetch.mockResponseOnce(JSON.stringify({ results: data }));

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

    const content = container.querySelector('.content');

    await wait();

    expect(content.querySelectorAll('.content--item').length).toBe(2);
});
Run Code Online (Sandbox Code Playgroud)

这是钩子实现:

const [data, setData] = useState([]);
const [error, setError] = useState('');

const fetchInitData = async () => {
    try {
        const res = await fetch(API_URL);
        const data = await res.json();

        if (data.fault) {
            setError('Rate limit Exceeded');
        } else {
            setData(data.results);
        }
    } catch(e) {
        setError(e.message);
    }
};

useEffect(() => {
    fetchInitData();
}, [isEqual(data)]);
Run Code Online (Sandbox Code Playgroud)

twi*_*ity 6

对于像我一样一年多后偶然发现这一问题的人来说,Giorgio 提到的问题已得到解决,并wait已被替换为waitFor,如此处记录:

https://testing-library.com/docs/dom-testing-library/api-async/

既然如此,我认为现在警告的解决方案应该是这样的:

import { render, waitFor } from '@testing-library/react';
// ...

it('should clear select content item', async () => {
    fetch.mockResponseOnce(JSON.stringify({ results: data }));

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

    const content = container.querySelector('.content');

    await waitFor(() =>
        expect(content.querySelectorAll('.content--item').length).toBe(2);
    );
});
Run Code Online (Sandbox Code Playgroud)

就我而言,我有一个App组件在钩子中异步加载数据useEffect,因此我在使用beforeEachrender 的每个测试中都会收到此警告App。这是我的案例的具体解决方案:

  beforeEach(async () => {
    await waitFor(() => render(<App />));
  });
Run Code Online (Sandbox Code Playgroud)


Gio*_*Gpx 5

这是一个已知问题,请在Github中查看此问题https://github.com/kentcdodds/react-testing-library/issues/281