测试使用Hooks获取数据的React组件 [英] Testing React components that fetches data using Hooks
问题描述
我的React应用程序具有一个组件,该组件从远程服务器获取要显示的数据.在预钩时代,componentDidMount()
是必须去的地方.但是现在我想为此使用钩子.
My React-application has a component that fetches data to display from a remote server. In the pre-hooks era, componentDidMount()
was the place to go. But now I wanted to use hooks for this.
const App = () => {
const [ state, setState ] = useState(0);
useEffect(() => {
fetchData().then(setState);
});
return (
<div>... data display ...</div>
);
};
我使用Jest和Enzyme进行的测试如下:
And my test using Jest and Enzyme looks like this:
import React from 'react';
import { mount } from 'enzyme';
import App from './App';
import { act } from 'react-test-renderer';
jest.mock('./api');
import { fetchData } from './api';
describe('<App />', () => {
it('renders without crashing', (done) => {
fetchData.mockImplementation(() => {
return Promise.resolve(42);
});
act(() => mount(<App />));
setTimeout(() => {
// expectations here
done();
}, 500);
});
});
测试成功,但是会记录一些警告:
The test succeeds, but it logs a few warnings:
console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: An update to App inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at (redacted)
in App (created by WrapperComponent)
in WrapperComponent
App组件的唯一更新发生在Promise回调中.如何确保在
The only update to the App component happens from the Promise callback. How can I ensure this happens within the act
block? The docs clearly suggest to have assertions happen outside the act
block. Besides, putting them inside doesn't change the warning.
推荐答案
酶不支持钩子,因为它是一个相对较新的功能: https://github.com/airbnb/enzyme/issues/2011
Enzyme doesn't have support for hooks since it's a relatively new feature: https://github.com/airbnb/enzyme/issues/2011
也许您可以同时使用纯Jest? 也不必担心警告,它应该在React 16.9.0发布时消失(请参见此拉取请求
Maybe you can use plain Jest in the meantime? Also don't worry about the warning, it's supposed to go away when React 16.9.0 is released (see this pull request https://github.com/facebook/react/pull/14853)
这篇关于测试使用Hooks获取数据的React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!