测试使用 Hooks 获取数据的 React 组件 [英] Testing React components that fetches data using Hooks

查看:23
本文介绍了测试使用 Hooks 获取数据的 React 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 React 应用程序有一个组件,可以从远程服务器获取要显示的数据.在前 hooks 时代,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 回调中.我怎样才能确保这在 act发生?文档明确建议在 act外部发生断言.此外,将它们放入里面并不会改变警告.

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.

推荐答案

该问题是由 Component 内部的许多更新引起的.

That issue is caused by many updates inside Component.

我遇到了同样的问题,这将解决问题.

I got the same issue, this would solve the issue.

await act( async () => mount(<App />));

这篇关于测试使用 Hooks 获取数据的 React 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆