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

todo list addtask

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

random quote generator

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

counter app increment

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.

reactjs_reference_api.htm
Advertisements