如何在我的集成测试中阻止未安装组件的 React 状态更新?
How can I prevent a React state update on an unmounted component in my integration testing?
我正在使用测试库编写我的测试。我正在编写加载组件的集成测试,然后尝试遍历测试中的 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)
以下是我写的jest集成测试。如果我注释掉其中一个测试,警告就会消失,但如果它们都 运行 那么我会收到警告。
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();
});
});
以下是组件:
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
是一个单例,你订阅了它的更改。
这意味着在您卸载第一个组件并安装第二个实例后,第一个仍然在那里注册,并且对 AccountHandler
的任何更新都将触发调用 setCurrentUser
和setPending
第一个组件。
组件卸载时需要取消订阅
像这样
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);
}
}, [])
AccountHandler 不是 singleton(),需要重构 getInstance 方法名称以反映这一点。因此,每次调用时都会创建一个新的 AccountHandler 实例。但是,register 函数将一个观察者添加到一个迭代的数组中,并且当身份验证状态发生变化时,每个观察者都会在该数组中被调用。当添加新的观察者时我没有清除,因此测试正在调用旧的和未安装的观察者以及新的观察者。通过简单地清除该阵列,问题就解决了。这是解决问题的更正代码:
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();
}
我正在使用测试库编写我的测试。我正在编写加载组件的集成测试,然后尝试遍历测试中的 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)
以下是我写的jest集成测试。如果我注释掉其中一个测试,警告就会消失,但如果它们都 运行 那么我会收到警告。
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();
});
});
以下是组件:
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
是一个单例,你订阅了它的更改。
这意味着在您卸载第一个组件并安装第二个实例后,第一个仍然在那里注册,并且对 AccountHandler
的任何更新都将触发调用 setCurrentUser
和setPending
第一个组件。
组件卸载时需要取消订阅
像这样
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);
}
}, [])
AccountHandler 不是 singleton(),需要重构 getInstance 方法名称以反映这一点。因此,每次调用时都会创建一个新的 AccountHandler 实例。但是,register 函数将一个观察者添加到一个迭代的数组中,并且当身份验证状态发生变化时,每个观察者都会在该数组中被调用。当添加新的观察者时我没有清除,因此测试正在调用旧的和未安装的观察者以及新的观察者。通过简单地清除该阵列,问题就解决了。这是解决问题的更正代码:
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();
}