My functional component uses the useEffect
hook to fetch data from an API on mount.(我的功能组件使用useEffect
挂钩从挂载的API中获取数据。)
I want to be able to test that the fetched data is displayed correctly.(我希望能够测试提取的数据是否正确显示。)
While this works fine in the browser, the tests are failing because the hook is asynchronous the component doesn't update in time.(尽管这在浏览器中可以正常工作,但由于挂钩是异步的,因此组件无法及时更新,因此测试失败。)
Live code: https://codesandbox.io/s/peaceful-knuth-q24ih?fontsize=14(实时代码: https : //codesandbox.io/s/peaceful-knuth-q24ih?fontsize=14)
App.js(App.js)
import React from "react";
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve(4), 400);
});
}
function App() {
const [members, setMembers] = React.useState(0);
React.useEffect(() => {
async function fetch() {
const response = await getData();
setMembers(response);
}
fetch();
}, []);
return <div>{members} members</div>;
}
export default App;
App.test.js(App.test.js)
import App from "./App";
import React from "react";
import { mount } from "enzyme";
describe("app", () => {
it("should render", () => {
const wrapper = mount(<App />);
console.log(wrapper.debug());
});
});
Besides that, Jest throws a warning saying: Warning: An update to App inside a test was not wrapped in act(...).
(除此之外,Jest发出警告说: Warning: An update to App inside a test was not wrapped in act(...).
)
I guess this is related?(我想这是相关的吗?)
How could this be fixed?(如何解决?)
ask by Andreas Remdt translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…