How to wrap into act(…) second/deferred/async rendering

你。 提交于 2021-01-29 10:25:44

问题


I have the following component:

function MyComp(props) {
    const [items, setItems] = useState([]);

    useEffect(() => { loadItems(); }, []);

    async function loadItems() {
        const result = await axios.get(`https://example.com/api`);
        setItems(result.data);
    }

    return (<div>{items.map(item => ...)}</div>);
}

And this test produces the act warning:

const items = { "data": [{"id": 1, "title": "Title1"}] };
axios.get.mockImplementationOnce(() => Promise.resolve(items)); 
const wrapper = mount(<MyComp />);

Warning: An update to MyComp inside a test was not wrapped in act(...).

From what I understand this happens because of the second update with fetched items. How to solve this issue?

EDIT: This helped

let wrapper = null;
await act(async () => {
    wrapper = mount(<MyComp />);
});

回答1:


Did you try?

    import { act } from 'react-dom/test-utils';

//...
    
        let wrapper = null;
        act(() => {
          wrapper = mount(<MyComp />);
        });

EDIT: here you can find more info https://reactjs.org/docs/testing-recipes.html#act




回答2:


The promise needs to be awaited before asserting the result. It can be obtained either by storing a reference to Promise.resolve(items) or getting it from a spy:

...
const wrapper = mount(<MyComp />);
expect(axios.get).toBeCalledTimes(1);
await axios.get.mock.results[0];
// assert the result


来源:https://stackoverflow.com/questions/64196742/how-to-wrap-into-act-second-deferred-async-rendering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!