- ReactJS Tutorial
- ReactJS - Home
- ReactJS - Introduction
- ReactJS - Installation
- ReactJS - Features
- ReactJS - Advantages & Disadvantages
- ReactJS - Architecture
- ReactJS - Creating a React Application
- ReactJS - JSX
- ReactJS - Components
- ReactJS - Nested Components
- ReactJS - Using Newly Created Components
- ReactJS - Component Collection
- ReactJS - Styling
- ReactJS - Properties (props)
- ReactJS - Creating Components using Properties
- ReactJS - props Validation
- ReactJS - Constructor
- ReactJS - Component Life Cycle
- ReactJS - Event management
- ReactJS - Creating an Event−Aware Component
- ReactJS - Introduce Events in Expense Manager APP
- ReactJS - State Management
- ReactJS - State Management API
- ReactJS - Stateless Component
- ReactJS - State Management Using React Hooks
- ReactJS - Component Life Cycle Using React Hooks
- ReactJS - Layout Component
- ReactJS - Pagination
- ReactJS - Material UI
- ReactJS - Http client programming
- ReactJS - Form Programming
- ReactJS - Controlled Component
- ReactJS - Uncontrolled Component
- ReactJS - Formik
- ReactJS - Conditional Rendering
- ReactJS - Lists
- ReactJS - Keys
- ReactJS - Routing
- ReactJS - Redux
- ReactJS - Animation
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - Table
- ReactJS - Managing State Using Flux
- ReactJS - Testing
- ReactJS - CLI Commands
- ReactJS - Building and Deployment
- ReactJS - Example
- Hooks
- ReactJS - Introduction to Hooks
- ReactJS - Using useState
- ReactJS - Using useEffect
- ReactJS - Using useContext
- ReactJS - Using useRef
- ReactJS - Using useReducer
- ReactJS - Using useCallback
- ReactJS - Using useMemo
- ReactJS - Custom Hooks
- ReactJS Advanced
- ReactJS - Accessibility
- ReactJS - Code Splitting
- ReactJS - Context
- ReactJS - Error Boundaries
- ReactJS - Forwarding Refs
- ReactJS - Fragments
- ReactJS - Higher Order Components
- ReactJS - Integrating With Other Libraries
- ReactJS - Optimizing Performance
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - React Without ES6 ECMAScript
- ReactJS - React Without JSX
- ReactJS - Reconciliation
- ReactJS - Refs and the DOM
- ReactJS - Render Props
- ReactJS - Static Type Checking
- ReactJS - Strict Mode
- ReactJS - Web Components
- Additional Concepts
- ReactJS - Date Picker
- ReactJS - Helmet
- ReactJS - Inline Style
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - Carousel
- ReactJS - Icons
- ReactJS - Form Components
- ReactJS - Reference API
- ReactJS Useful Resources
- ReactJS - Quick Guide
- ReactJS - Useful Resources
- ReactJS - Discussion
ReactJS - scryRenderedComponentsWithType()
The scryRenderedComponentsWithType() function in the React Testing Library is a useful tool for testing React components. This function searches our rendered component tree for each instance of components of a given type.
Consider our React project to be a tree its multiple components are branches. The scryRenderedComponentsWithType() function functions as a search engine, allowing us to find all instances of a specific type of component within that tree.
In other words we can say that the scryRenderedComponentsWithType() function in the React Testing Library is useful for locating instances of components based on their type.
Syntax
scryRenderedComponentsWithType(tree, componentClass)
Parameters
tree − This is the complete React component hierarchy. We can consider it like the entire forest.
componentClass − This is the type of component we are looking for, just like a certain tree in the forest.
Return Value
scryRenderedComponentsWithType(tree, componentClass) scans the tree and returns all instances of the given component type.
Examples
Example − Todo List App and Testing
So first we are going to create a simple todo list app in which users can add, delete, and mark tasks as done. And then we will create a test file with a testing library, like Jest or React Testing Library. To find components of certain types in the test file we will use scryRenderedComponentsWithType(). So below is the code for the Todo List App and its test code −
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); });
Output
Example − Random Quote Generator App
So now we are going to create a random quote generator app. The app allows users to produce new quotes as many times as they want to get a repeatable and entertaining experience. And also we will write testing code using the scryRenderedComponentsWithType() method to test our newly created app. So code for this app is as follows −
// 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); });
Output
Example − Counter App and Testing
This time we are going to create a Counter App which is an easy application that allows users to interact with a counter. Users can increment, decrement, and reset the counter to zero. This app is a basic example that teaches us about React state management. So we will create a test code for this app using the scryRenderedComponentsWithType() method. Code for the app and testing is as follows −
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); });
Output
Remember that these are simple examples of how to use scryRenderedComponentsWithType() in testing scenarios. In real-life situations, we would have more complete tests that cover many parts of the functionality of our components.
Install and configure the necessary testing libraries (like Jest and React Testing Library) and the testing environment.
Summary
If we have a React app that consists of multiple components like buttons, forms, and headers, we can use the scryRenderedComponentsWithType() function to find all instances. Understanding and using scryRenderedComponentsWithType() can be useful in our testing process. It makes sure that our components render properly and makes testing more efficient.
To Continue Learning Please Login
Login with Google