如何在集成测试中阻止未安装组件上的React状态更新?

布拉德·琼斯

我正在使用测试库来编写测试。我正在编写用于加载组件的集成测试,然后尝试在测试中遍历UI以模仿用户可能执行的操作,然后测试这些步骤的结果。在我的测试输出中,当两个测试都运行时,我将收到以下警告,但仅运行一个测试时,则不会得到以下警告。所有运行的测试均成功通过。

  console.error node_modules/react-dom/cjs/react-dom.development.js:88
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    in Unknown (at Login.integration.test.js:12)

以下是我开玩笑编写的集成测试。如果我注释掉其中任何一个测试,警告都会消失,但是如果它们同时运行,则会收到警告。

import React from 'react';
import { render, screen, waitForElementToBeRemoved, waitFor } from '@testing-library/react';
import userEvent from "@testing-library/user-event";
import { login } from '../../../common/Constants';
import "@testing-library/jest-dom/extend-expect";
import { MemoryRouter } from 'react-router-dom';
import App from '../../root/App';
import { AuthProvider } from '../../../middleware/Auth/Auth';

function renderApp() {
  render(
    <AuthProvider>
      <MemoryRouter>
        <App />
      </MemoryRouter>
    </AuthProvider>
  );

  //Click the Login Menu Item
  const loginMenuItem = screen.getByRole('link', { name: /Login/i });
  userEvent.click(loginMenuItem);

  //It does not display a login failure alert
  const loginFailedAlert = screen.queryByRole('alert', { text: /Login Failed./i });
  expect(loginFailedAlert).not.toBeInTheDocument();

  const emailInput = screen.getByPlaceholderText(login.EMAIL);
  const passwordInput = screen.getByPlaceholderText(login.PASSWORD);
  const buttonInput = screen.getByRole('button', { text: /Submit/i });

  expect(emailInput).toBeInTheDocument();
  expect(passwordInput).toBeInTheDocument();
  expect(buttonInput).toBeInTheDocument();

  return { emailInput, passwordInput, buttonInput }
}

describe('<Login /> Integration tests:', () => {

  test('Successful Login', async () => {
    const { emailInput, passwordInput, buttonInput } = renderApp();

    Storage.prototype.getItem = jest.fn(() => {
      return JSON.stringify({ email: '[email protected]', password: 'asdf' });
    });

    // fill out and submit form with valid credentials
    userEvent.type(emailInput, '[email protected]');
    userEvent.type(passwordInput, 'asdf');
    userEvent.click(buttonInput);

    //It does not display a login failure alert
    const noLoginFailedAlert = screen.queryByRole('alert', { text: /Login Failed./i });
    expect(noLoginFailedAlert).not.toBeInTheDocument();

    // It hides form elements
    await waitForElementToBeRemoved(() => screen.getByPlaceholderText(login.EMAIL));
    expect(emailInput).not.toBeInTheDocument();
    expect(passwordInput).not.toBeInTheDocument();
    expect(buttonInput).not.toBeInTheDocument();
  });


  test('Failed Login - invalid password', async () => {
    const { emailInput, passwordInput, buttonInput } = renderApp();

    Storage.prototype.getItem = jest.fn(() => {
      return JSON.stringify({ email: '[email protected]', password: 'asdf' });
    });

    // fill out and submit form with invalid credentials
    userEvent.type(emailInput, '[email protected]');
    userEvent.type(passwordInput, 'invalidpw');
    userEvent.click(buttonInput);

    //It displays a login failure alert
    await waitFor(() => expect(screen.getByRole('alert', { text: /Login Failed./i })).toBeInTheDocument())

    // It still displays login form elements
    expect(emailInput).toBeInTheDocument();
    expect(passwordInput).toBeInTheDocument();
    expect(buttonInput).toBeInTheDocument();
  });
});

以下是组件:

import React, { useContext } from 'react';
import { Route, Switch, withRouter } from 'react-router-dom';
import Layout from '../../hoc/Layout/Layout';
import { paths } from '../../common/Constants';
import LandingPage from '../pages/landingPage/LandingPage';
import Dashboard from '../pages/dashboard/Dashboard';
import AddJob from '../pages/addJob/AddJob';
import Register from '../pages/register/Register';
import Login from '../pages/login/Login';
import NotFound from '../pages/notFound/NotFound';
import PrivateRoute from '../../middleware/Auth/PrivateRoute';
import { AuthContext } from '../../middleware/Auth/Auth';

function App() {

  let authenticatedRoutes = (
    <Switch>
      <PrivateRoute path={'/dashboard'} exact component={Dashboard} />
      <PrivateRoute path={'/add'} exact component={AddJob} />
      <PrivateRoute path={'/'} exact component={Dashboard} />
      <Route render={(props) => (<NotFound {...props} />)} />
    </Switch>
  )

  let publicRoutes = (
    <Switch>
      <Route path='/' exact component={LandingPage} />
      <Route path={paths.LOGIN} exact component={Login} />
      <Route path={paths.REGISTER} exact component={Register} />
      <Route render={(props) => (<NotFound {...props} />)} />
    </Switch>
  )

  const { currentUser } = useContext(AuthContext);
  let routes = currentUser ? authenticatedRoutes : publicRoutes;

  return (
    <Layout>{routes}</Layout>
  );
}

export default withRouter(App);

以下是包装在renderApp()函数中的AuthProvider组件。它利用React useContext挂钩的优势来管理应用程序的用户身份验证状态:

import React, { useEffect, useState } from 'react'
import { AccountHandler } from '../Account/AccountHandler';

export const AuthContext = React.createContext();

export const AuthProvider = React.memo(({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [pending, setPending] = useState(true);

  useEffect(() => {
    if (pending) {
      AccountHandler.getInstance().registerAuthStateChangeObserver((user) => {
        setCurrentUser(user);
        setPending(false);
      })
    };
  })

  if (pending) {
    return <>Loading ... </>
  }
  return (
    <AuthContext.Provider value={{ currentUser }}>
      {children}
    </AuthContext.Provider>
  )
});

似乎第一个测试安装了被测组件,但是第二个测试却以某种方式试图引用第一个安装的组件,而不是新安装的组件,但是我似乎无法弄清楚这里正在发生什么情况以纠正这些警告。任何帮助将不胜感激!

布拉德·琼斯

如果AccountHandler不是singleton(),则需要重构getInstance方法名称以反映这一点。因此,每次调用AccountHandler时都会创建一个新实例。但是,寄存器功能将观察者添加到迭代的数组中,并且当身份验证状态更改时,该数组中的每个观察者都会被调用。我并不清楚何时添加新的观察者,因此测试既调用了旧观察者,也调用了未安装的观察者。通过简单地清除该阵列,该问题得以解决。这是已解决问题的更正代码:

  private observers: Array<any> = [];

  /**
   * 
   * @param observer a function to call when the user authentication state changes
   * the value passed to this observer will either be the email address for the 
   * authenticated user or null for an unauthenticated user.
   */
  public registerAuthStateChangeObserver(observer: any): void {
    /**
     * NOTE:
     * * The observers array needs to be cleared so as to avoid the 
     * * situation where a reference to setState on an unmounted
     * * React component is called.  By clearing the observer we 
     * * ensure that all previous observers are garbage collected
     * * and only new observers are used.  This prevents memory
     * * leaks in the tests.
     */
    this.observers = [];

    this.observers.push(observer);
    this.initializeBackend();
  }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在我的应用程序中避免“无法在未安装的组件上执行 React 状态更新”错误?

React Testing Library测试仍然出现“未安装组件上的反应状态更新”错误

React:无法在未安装的组件上执行React状态更新

ReactJS:无法在未安装的组件上执行React状态更新

无法在未安装的组件上执行React状态更新

无法在React中的未安装组件上执行React状态更新

无法在React js和Firestore中的未安装组件上执行React状态更新

未安装的组件上的状态更新如何导致内存泄漏?

警告:无法在SceneView(由Pager创建)中的未安装组件上执行React状态更新

无法对 reactjs 中未安装的组件执行 React 状态更新

如何修复无法对 reactjs 中的未安装组件警告执行 React 状态更新

如何防止在 React 中未安装的组件中设置状态?

如何修复 TypeError:无法读取未定义的属性“randomProperty”+警告“无法在未安装的组件上执行 React 状态更新”

React测试库:测试内部的更新未包装在act(...)中,并且无法在已卸载的组件上执行React状态更新

React useEffect导致:无法在未安装的组件上执行React状态更新

React Native无法在未安装的组件Firebase上执行React状态更新

React useState 导致“无法在未安装的组件上执行 React 状态更新..”错误

如何在React组件上测试道具更新

useEffect-无法在未安装的组件上执行React状态更新

无法使用获取POST方法在未安装的组件上执行React状态更新

修复“无法在未安装的组件上执行React状态更新”错误

修复方法:警告:无法在未安装的组件上执行React状态更新

React无法对未安装的组件错误执行React状态更新

React - 无法对未安装的组件执行 React 状态更新

React:如何在功能组件中强制状态更新?

警告:无法在未安装的组件上执行反应状态更新

如何删除警告“无法在未安装的组件上执行反应状态更新”

无法对Interval函数中的未安装组件问题执行React状态更新

reactstrap 模式中的 Graphql 突变 - 无法对未安装的组件执行 React 状态更新