首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在集成测试中防止未安装组件上的React状态更新?

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

Stack Overflow用户
提问于 2020-10-01 03:01:52
回答 2查看 895关注 0票数 0

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

代码语言:javascript
复制
  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)

下面是我用jest编写的集成测试。如果我注释掉这两个测试中的任何一个,警告就会消失,但如果它们都运行,我就会得到警告。

代码语言:javascript
复制
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: 'asdf@asdf.com', password: 'asdf' });
    });

    // fill out and submit form with valid credentials
    userEvent.type(emailInput, 'asdf@asdf.com');
    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: 'brad@asdf.com', password: 'asdf' });
    });

    // fill out and submit form with invalid credentials
    userEvent.type(emailInput, 'brad@asdf.com');
    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();
  });
});

以下是组件:

代码语言:javascript
复制
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钩子来管理应用程序的用户身份验证状态:

代码语言:javascript
复制
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>
  )
});

看起来好像第一个测试挂载了被测试的组件,但第二个测试以某种方式试图引用第一个挂载的组件,而不是新挂载的组件,但我似乎无法弄清楚这里到底发生了什么来纠正这些警告。任何帮助都将不胜感激!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-08 21:01:06

AccountHandler不是单例(),需要重构getInstance方法名以反映这一点。因此,每次调用它时都会创建一个新的AccountHandler实例。但是,register函数将一个观察者添加到迭代的数组中,当身份验证状态更改时,将在该数组中调用每个观察者。我没有清除什么时候添加了新的观察者,因此测试调用了旧的和未挂载的观察者以及新的观察者。只需清除该数组,问题就解决了。以下是已修复该问题的更正代码:

代码语言:javascript
复制
  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();
  }

票数 1
EN

Stack Overflow用户

发布于 2020-10-03 06:22:23

看起来您的AccountHandler是一个单例,您需要订阅对它的更改。

这意味着在卸载第一个组件并挂载第二个实例后,第一个组件仍然在那里注册,并且对AccountHandler的任何更新都将触发处理程序,该处理程序也会调用第一个组件的setCurrentUsersetPending

卸载组件时需要取消订阅。

像这样的东西

代码语言:javascript
复制
const handleUserChange = useCallback((user) => {
  setCurrentUser(user);
  setPending(false);
}, []);

useEffect(() => {
  if (pending) { 
    AccountHandler.getInstance().registerAuthStateChangeObserver(handleUserChange)
  };

  return () => {
    // here you need to unsubscribe
    AccountHandler.getInstance().unregisterAuthStateChangeObserver(handleUserChange);
  }
}, [])

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64144143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档