React 测试库中的 scryRenderedComponentsWithType() 函数是用于测试 React 组件的有用工具。此函数在渲染的组件树中搜索给定类型的组件的每个实例。
将我们的 React 项目视为一棵树,它的多个组件是分支。scryRenderedComponentsWithType() 函数用作搜索引擎,使我们能够在该树中找到特定类型组件的所有实例。
换句话说,我们可以说 React 测试库中的 scryRenderedComponentsWithType() 函数对于根据组件的类型定位组件实例很有用。
语法
scryRenderedComponentsWithType(tree, componentClass)
参数
- tree - 这是完整的 React 组件层次结构。我们可以把它看作是整个森林。
- componentClass - 这就是我们正在寻找的组件类型,就像森林中的某棵树一样。
返回值
scryRenderedComponentsWithType(tree, componentClass) 扫描树并返回给定组件类型的所有实例。
例子
示例 - 待办事项列表应用程序和测试
因此,首先,我们将创建一个简单的待办事项列表应用程序,用户可以在其中添加、删除任务并将任务标记为已完成。然后我们将创建一个带有测试库的测试文件,例如 Jest 或 React 测试库。为了在测试文件中查找某些类型的组件,我们将使用 scryRenderedComponentsWithType()。因此,以下是Todo List App的代码及其测试代码 -
ToDoListApp.js
import React, { useState } from 'react';
const ToDoListApp = () => {
const [tasks, setTasks] = useState([]);
const [newTask, setNewTask] = useState('');
const addTask = () => {
if (newTask.trim() !== '') {
setTasks([...tasks, newTask]);
setNewTask('');
}
};
const removeTask = (index) => {
const updatedTasks = [...tasks];
updatedTasks.splice(index, 1);
setTasks(updatedTasks);
};
return (
<div>
<h2>To-Do List</h2>
<input
type="text"
value={newTask}
onChange={(e) => setNewTask(e.target.value)}
/>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map((task, index) => (
<li key={index}>
{task}
<button onClick={() => removeTask(index)}>Remove</button>
</li>
))}
</ul>
</div>
);
};
export default ToDoListApp;
ToDoListApp.test.js
import React from 'react';
import { render, scryRenderedComponentsWithType } from '@testing-library/react';
import ToDoListApp from './ToDoListApp';
test('renders the To-Do List App', () => {
// Render the component
const { container } = render(<ToDoListApp />);
// find instances of buttons
const buttons = scryRenderedComponentsWithType(container, 'button');
expect(buttons.length).toBeGreaterThan(0);
});
输出
示例 - 随机报价生成器应用程序
所以现在我们要创建一个随机报价生成器应用程序。该应用程序允许用户根据需要多次生成新报价,以获得可重复和有趣的体验。此外,我们还将使用 scryRenderedComponentsWithType() 方法编写测试代码来测试我们新创建的应用程序。所以这个应用程序的代码如下 -
// RandomQuoteGeneratorApp.js
import React, { useState } from 'react';
import './App.css';
const RandomQuoteGeneratorApp = () => {
const quotes = [
"Opportunities don't happen, you create them.",
"Love your family, work super hard, live your passion.",
"Life is what happens when you are busy making other plans."
];
const [randomQuote, setRandomQuote] = useState('');
const generateRandomQuote = () => {
const randomIndex = Math.floor(Math.random() * quotes.length);
setRandomQuote(quotes[randomIndex]);
};
return (
<div className='App'>
<h2>Random Quote Generator</h2>
<button onClick={generateRandomQuote}>Generate Quote</button>
{randomQuote && <p>"{randomQuote}"</p>}
</div>
);
};
export default RandomQuoteGeneratorApp;
RandomQuoteGeneratorApp.test.js
import React from 'react';
import { render, scryRenderedComponentsWithType } from '@testing-library/react';
import RandomQuoteGeneratorApp from './RandomQuoteGeneratorApp';
test('renders the Random Quote Generator App', () => {
// Render the component
const { container } = render(<RandomQuoteGeneratorApp />);
// find instances of button elements
const buttonElements = scryRenderedComponentsWithType(container, 'button');
expect(buttonElements.length).toBeGreaterThan(0);
});
输出
示例 - 计数器应用程序和测试
这次我们将创建一个计数器应用程序,这是一个简单的应用程序,允许用户与计数器交互。用户可以增加、减少计数器并将计数器重置为零。这个应用程序是一个基本示例,它教我们关于 React 状态管理的知识。因此,我们将使用 scryRenderedComponentsWithType() 方法为此应用程序创建测试代码。应用程序和测试的代码如下 -
CounterApp.js
import React, { useState } from 'react';
import './App.css';
const CounterApp = () => {
const [counter, setCounter] = useState(0);
const increment = () => {
setCounter(counter + 1);
};
const decrement = () => {
setCounter(counter - 1);
};
const reset = () => {
setCounter(0);
};
return (
<div className='App'>
<h2>Counter App</h2>
<p>Counter Value: {counter}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
};
export default CounterApp;
CounterApp.test.js
import React from 'react';
import { render, scryRenderedComponentsWithType } from '@testing-library/react';
import CounterApp from './CounterApp';
test('renders the Counter App', () => {
// Render the component
const { container } = render(<CounterApp />);
// find instances of button elements
const buttonElements = scryRenderedComponentsWithType(container, 'button');
expect(buttonElements.length).toBeGreaterThanOrEqual(3);
});
输出
请记住,这些是如何在测试场景中使用 scryRenderedComponentsWithType() 的简单示例。在现实生活中,我们将进行更完整的测试,这些测试涵盖了我们组件功能的许多部分。
安装并配置必要的测试库(如 Jest 和 React 测试库)和测试环境。
总结
如果我们有一个由按钮、表单和标题等多个组件组成的 React 应用程序,我们可以使用 scryRenderedComponentsWithType() 函数来查找所有实例。理解和使用 scryRenderedComponentsWithType() 在我们的测试过程中非常有用。它确保我们的组件正确呈现,并使测试更加高效。