@testing-library/react 测试组件中使用 useState 初始化状态的示例
在使用 @testing-library/react 测试组件时,我们可以使用 'render' 方法来渲染组件,并通过 'screen' 对象来查询和操作渲染后的 DOM 元素。如果组件中使用了 'useState' 定义了状态,我们需要在测试中模拟这些状态的初始化值。以下是三个不同使用方式的示例:
- 布尔类型的状态
在组件中定义一个布尔类型的状态:
function MyComponent() {
const [isOpened, setIsOpened] = useState(false);
// ...
}
在测试中,我们可以使用 'render' 方法返回的对象中的 'result' 属性访问到组件实例,然后通过 'result.current' 来访问到组件的状态。我们可以通过 'result.current[0]' 来获取到 'isOpened' 的值,然后断言是否为初始值 'false':
import { render } from '@testing-library/react';
test('should initialize isOpened to false', () => {
const { result } = render(<MyComponent />);
expect(result.current[0]).toBe(false);
});
- 对象类型的状态
在组件中定义一个对象类型的状态:
function MyComponent() {
const [user, setUser] = useState({
name: 'John',
age: 30,
});
// ...
}
在测试中,我们可以使用 'result.current[0]' 来获取到 'user' 对象的值,然后断言是否为初始值:
test('should initialize user to {name: 'John', age: 30}', () => {
const { result } = render(<MyComponent />);
expect(result.current[0]).toEqual({
name: 'John',
age: 30,
});
});
- 数组类型的状态
在组件中定义一个数组类型的状态:
function MyComponent() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Buy milk', completed: false },
{ id: 2, text: 'Take out the trash', completed: true },
]);
// ...
}
在测试中,我们可以使用 'result.current[0]' 来获取到 'todos' 数组的值,然后断言是否为初始值:
test('should initialize todos to [{id: 1, text: 'Buy milk', completed: false}, {id: 2, text: 'Take out the trash', completed: true}]', () => {
const { result } = render(<MyComponent />);
expect(result.current[0]).toEqual([
{ id: 1, text: 'Buy milk', completed: false },
{ id: 2, text: 'Take out the trash', completed: true },
]);
});
注意,如果测试中不需要使用到某些状态,可以直接使用 'result.current' 访问到整个状态对象,而不需要单独访问某个属性。此外,如果某个状态作为判断条件且不显示在页面中,我们可以使用 'screen.getByRole' 方法来查询页面中是否存在某个元素,然后断言其是否存在或不存在来判断该状态的值。例如:
function MyComponent() {
const [isModalOpen, setIsModalOpen] = useState(false);
const handleButtonClick = () => setIsModalOpen(true);
// ...
return (
<div>
<button onClick={handleButtonClick}>Open modal</button>
{isModalOpen && <Modal />}
</div>
);
}
test('should open modal when 'Open modal' button is clicked', () => {
render(<MyComponent />);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
fireEvent.click(screen.getByText('Open modal'));
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
在上面的例子中,我们使用 'screen.getByRole' 方法来查询页面中是否存在 'role=dialog' 的元素,即是否存在打开的模态框。在初始状态下,我们期望页面中不存在这个元素,因此使用 'screen.queryByRole' 方法来查询。在点击按钮后,我们期望页面中存在这个元素,因此使用 'screen.getByRole' 方法来查询,并断言其是否存在。由于这个状态不需要显示在页面中,我们可以直接通过页面元素来判断其值。
原文地址: https://www.cveoy.top/t/topic/okP4 著作权归作者所有。请勿转载和采集!