问题
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