当我们使用 React 构建 Web 应用程序时,测试我们的组件非常重要。这就像检查一切是否按预期进行。为了解决这个问题,React 中有一个名为 act() 的工具。它伪装成一个 Web 浏览器,并确保我们的组件能够正确地相互通信。
因此,act() 就像一个帮助器,它确保你的组件在你测试它们时按照它们应有的方式运行。它就像一个小助手,可以帮助您正确进行测试。
act() 是一个函数,它通过验证 React 组件的行为是否像在真实的 Web 浏览器中操作一样来支持我们。对于执行异步任务(如数据提取、更新或用户交互)的组件来说,这一点尤为重要。
语法
import { act } from 'react-dom/test-utils';
act(() => {
// The code to interact with React components
});
参数
act() 函数接受单个输入,该输入是一个包含我们将要测试的代码的函数。与 React 组件的任何交互,如渲染、点击或表单提交都应该包含在此代码中。
返回值
React 中的 act() 方法不返回任何内容。
例子
示例 - 状态更改应用程序
提供的代码是一个名为 MyComponent 的简单 React 组件及其使用 @testing-library/react 和 @testing-library/user-event 库的相应测试。组件的初始状态设置为“初始状态”。该测试呈现 MyComponent。它使用 userEvent.click 模拟按钮单击。单击按钮时,组件的状态将更新为“新状态”。该测试断言文本“New State”存在于呈现的输出中。
// MyComponent.js
import React, { useState } from 'react';
const MyComponent = () => {
const [currentState, setCurrentState] = useState('Initial State');
const handleButtonClick = () => {
setCurrentState('New State');
};
return (
<div>
<p>{currentState}</p>
<button onClick={handleButtonClick}>Click me</button>
</div>
);
};
export default MyComponent;
MyComponent.test.js
import { render, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MyComponent from './MyComponent';
test('updates state on button click', () => {
// Render the component
render(<MyComponent />);
// Use act() to interact with the component
act(() => {
userEvent.click(screen.getByRole('button'));
});
// Assert the expected state
expect(screen.getByText('New State')).toBeInTheDocument();
});
输出
示例 - 异步组件
在这个应用程序中,我们将有一个名为 MyAsyncComponent 的 React 组件,它使用 fetchData 函数模拟异步数据获取。此外,此组件还有一个测试代码,使用 @testing-library/react 库和 act 函数来处理异步操作。因此,该应用程序的代码及其各自的测试文件如下 -
// MyAsyncComponent.js
import React, { useState, useEffect } from 'react';
const fetchData = () => {
return new Promise((resolve) => {
// asynchronous data fetching
setTimeout(() => {
resolve('Fetched Data');
}, 1000);
});
};
const MyAsyncComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchDataAsync = async () => {
const result = await fetchData();
setData(result);
};
fetchDataAsync();
}, []);
return (
<div>
<p>{data ? data : 'Loading...'}</p>
</div>
);
};
export default MyAsyncComponent;
MyAsyncComponent.test.js
import { render, screen, act } from '@testing-library/react';
import MyAsyncComponent from './MyAsyncComponent';
test('renders data after fetching', async () => {
// Render the component
render(<MyAsyncComponent />);
// Use act() to wait for the asynchronous data fetching
await act(async () => {
});
expect(screen.getByText('Fetched Data')).toBeInTheDocument();
});
输出
示例 - 计数器应用程序
让我们看一个例子。我们有一个带有按钮的 Counter 组件。因此,当我们按下按钮时,它将增加计数器并更新标题。因此,为了创建此应用程序,我们将按照以下步骤操作 -
设置测试环境
- 在每次测试之前创建一个容器元素。
- 每次测试后取出容器。
组件测试
- 我们将使用 act() 函数来包装组件的渲染。这确保了 React 在浏览器中正常运行。
- act() 函数可用于提供用户交互(如单击按钮)。
// Code for Counter component
// Set up a container for rendering the component
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('can render and update a counter', () => {
// Test first render and componentDidMount
act(() => {
ReactDOM.createRoot(container).render(<Counter />);
});
// A click event
act(() => {
button.dispatchEvent(new MouseEvent('click', {bubbles: true}));
});
});
总结
act() 是一个工具,允许我们测试 React 组件,尤其是在我们处理异步操作或 DOM 交互时。通过使用 act(),我们可以确保我们的测试正确地遵循我们的组件在真实 Web 浏览器中的行为。测试是创建可靠且无错误的程序的重要组成部分,而 act() 在此过程中是一个有用的函数。