Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to Optimize the Performance of React-Redux Applications?
Next article icon

How to test React-Redux applications?

Last Updated : 28 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Testing React-Redux applications is crucial to ensure their functionality, reliability, and maintainability. As we know, the React-Redux application involves complex interactions between components and Redux state management, testing helps us to identify and prevent bugs, regressions, and performance issues. In this article, we will explore various approaches to testing React-Redux applications.

Table of Content

  • Effective Testing Strategies for React-Redux Applications
  • 1. Testing React Components
  • 2. Testing Redux Actions
  • 3. Testing Redux Reducers
  • Conclusion

Effective Testing Strategies for React-Redux Applications

Testing React-Redux applications involves a combination of unit testing for React components, actions, and reducers, alongside integration testing for the Redux store. By meticulously testing each aspect of the application, we can ensure functionality, reliability, and maintainability, resulting in a robust user experience.

Steps to Create a React and Redux Text App

Step 1: Create a React application using the following command

npx create-react-app text-app

Step 2: After creating your project folder i.e. text-app, move to it using the following command

cd text-app

Step 3: Once you are done creating the ReactJS application, install redux using the following command

npm install react-redux @reduxjs/toolkit

Step 4: After installing Redux, install the redux-mock-store to mock the redux store.

npm install redux-mock-store

Step 5: We can start the application using this command.

npm start

Step 6: We can test the application using this command, or we can modify the test script inside package.json.

npm run test

Project Structure:

Screenshot-2024-04-07-at-33013-PM-min
Project Structure

The updated dependencies in the package.json file will look like

"dependencies": {
"@reduxjs/toolkit": "^2.2.2",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"jest": "^27.5.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-scripts": "5.0.1",
"redux-mock-store": "^1.5.4"
}

Explanation:

  • These integrated codes demonstrate the implementation of a React and Redux application.
  • The Redux setup involves creating a store with configureStore and assigning a slice reducer, textReducer, to handle text state updates. This reducer, defined using createSlice, contains actions for setting and clearing text.
  • In the React component, named App, useDispatch is utilized to dispatch actions, such as setText, which updates the text state with the payload passed from the input field.
  • The handleChange function captures user input and dispatches the appropriate action, ensuring that the payload is sent to the reducer for state modification.

Example: In this example, we've implemented an input box that dynamically updates the header text as we type into it. See the code example below:

JavaScript
// filename - ./src/index.js  import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { Provider } from 'react-redux'; import store from './redux/store';  const root = ReactDOM.createRoot(document.getElementById('root'));  root.render(     <React.StrictMode>          {/* wrapping the app inside store provider */}         <Provider store={store}>             <App />         </Provider>      </React.StrictMode> );  reportWebVitals(); 
JavaScript
// filename - ./src/App.js  import { useDispatch, useSelector } from 'react-redux'; import './App.css'; import { setText } from './redux/features/textSlice';   function App() {      const dispatch = useDispatch();     const { text } = useSelector(state => state.text);      // whenever we type any data on the input      const handleChange = (event) => {         dispatch(setText(event.target.value?.toUpperCase()));     }      return (         <>             <div className='container'>                 <h2>                     Text: {text}                 </h2>                 <div className='input-box'>                     <input type="text" name='text' onChange={handleChange} placeholder="Enter text"/>                 </div>             </div>         </>     ); }  export default App; 
JavaScript
// filename - ./src/redux/features/textSlice.js  import { createSlice } from "@reduxjs/toolkit";   // initial global state of the app const initialState = {     text: "" }  // create a slice object const textSlice = createSlice({     name: "text",     initialState,      // creating reducers to manipulate state     reducers: {         setText: (state, action) => {             state.text = action.payload;         },         clearText: (state, action) => {             state.text = "";         }     } });   // exporting actions and reducers export const { setText, clearText } = textSlice.actions; export default textSlice.reducer; 
JavaScript
import { configureStore } from "@reduxjs/toolkit"; import textReducer from "../features/textSlice";   // create a store for the redux application const store = configureStore({     reducer: {         text: textReducer     } });  export default store; 

Output:

Screen-Recording-2024-04-07-at-41517-PM
Output of the above implementation

1. Testing React Components

React components are the building blocks of a React-Redux application's user interface. Testing these components ensures that the components are rendered correctly and behave as expected under different scenarios. Testing React components in React-Redux applications involves mocking the redux store and to mock the redux store we will use the redux-mock-store package.

Example: The below code snippets illustrate the test code for the React components.

JavaScript
// filename - ./src/__tests__/components/App.test.js  import { render, screen } from '@testing-library/react'; import { Provider } from 'react-redux'; import configureMockStore from 'redux-mock-store'; import App from '../../App';  // mocking redux store to mimic the actual redux store const mockStore = configureMockStore([]); const initialState = { text: "" }; const store = mockStore(initialState);  // Testing the App.js component describe('Testing App Component', () => {      test('The "text" string is rendered correctly', () => {          // rendering the App component         render(<Provider store={store}> <App /> </Provider>);          /*          now, find the particular element that will          appear after mounting the App component          */         const element = screen.getByText('Text:');          // assert that the element is found         expect(element).toBeInTheDocument();     });      test('The input element is correctly rendered', () => {          // rendering the App component         render(<Provider store={store}> <App /> </Provider>);          // selecting input element by the placeholder text         const inputElement = screen.getByPlaceholderText('Enter text');          // assert that the input element is found         expect(inputElement).toBeInTheDocument();     }); }); 

Output:

Screenshot-2024-04-07-at-43544-PM-min
Test Result for App.test.js

Explanation:

The above code demonstrates, how we test React components. To test the component, we mock the redux store using the redux-mock-store package. With this step, We proceed to test two major aspects of the App component.

  • Firstly, we ensure that the component correctly renders the string "Text:".
  • Secondly, we verify whether the input box is rendered as expected.

By using these approaches, we validate the rendering of the user interface (UI) of the App component.

2. Testing Redux Actions

Testing Redux Actions is an important aspect of ensuring the correctness and reliability of Redux State Management in the React-Redux application. The Redux-Actions are responsible for describing changes to the application state, and testing them ensures that these changes are dispatched correctly and result in the expected state updates. The Redux-Actions objects consist of two values, the first one is type, which denotes the type of action being performed and the other one is payload, which carries any additional data associated with the action.

Example: The below code snippets illustrates the test code for the Redux Actions.

JavaScript
import configureMockStore from 'redux-mock-store'; import {     setText,     clearText } from '../../redux/features/textSlice';   // mocking redux store to mimic the actual redux store const mockStore = configureMockStore([]); const initialState = { text: "" }; const store = mockStore(initialState);  // testing the redux actions created in features/textSlice.js describe('Testing Redux Actions', () => {      /*clear the actions after each test,      to start each test with a clean state      */     beforeEach(() => {         store.clearActions();     });      test('Testing "setText" action dispatches correct action with payload', () => {          // pass any text to dispatch the "text/setText" actions         const payloadData = "any text"         store.dispatch(setText(payloadData));          // getting dispatched actions and expected actions         const actions = store.getActions();         const expectedAction = { type: 'text/setText', payload: payloadData };          // assert that the action is dispatched correctly         expect(actions).toEqual([expectedAction]);     });      test('Testing "clearText" action dispatches correct action, no need of any payload', () => {          // dispatch the "text/clearText" actions         store.dispatch(clearText());          // getting dispatched actions and expected actions         const actions = store.getActions();         const expectedAction = { type: 'text/clearText' };          // assert that the action is dispatched correctly         expect(actions).toEqual([expectedAction]);     }); }); 

Output:

Screenshot-2024-04-07-at-60943-PM-min
Test Result for textActions.test.js

Explanation:

The above code demonstrates the testing of the Redux Actions. To test the actions, we mock the redux store using the redux-mock-store package. After mocking the store, we are testing two specific actions

  • The setText action: The action is responsible for updating the text state in the redux store. It takes a payloadData parameter, which represents the text value to be set. When dispatched, it creates an action object with the type set to 'text/setText' and the payload set to the provided payload.
  • The clearText action: The action clears the text state in the Redux store. It does not require any payload, as it simply resets the text to an empty string. When dispatched, it creates an action object with the type set to 'text/clearText' with no payload.

By testing these actions, we ensure that they correctly generate the expected action when dispatched, which ensures the proper functioning of the Redux state management system within our application.

3. Testing Redux Reducers

Redux reducers specify how the application's state changes in response to actions dispatched to the Redux store. Testing Redux reducers ensures that it updates the state correctly and produces expected outcomes.

Example: The below code snippets illustrate the test code for the Redux Reducers.

JavaScript
// filename - ./src/__tests__/features/textReducers.test.js  import textReducer, {     setText,     clearText } from '../../redux/features/textSlice';   // testing the redux actions created in features/textSlice.js describe('Testing Redux Reducers', () => {      test('Testing "setText" reducers', () => {          // here we have initial state and payload text to set         const initialState = { text: '' };         const payloadData = 'Hello';          // calling the setText function to set the text using textReducer         const action = setText(payloadData);         const newState = textReducer(initialState, action);          // assert that the setText function work properly         expect(newState.text).toBe(payloadData);     });      test('Testing "clearText" reducers', () => {          // updated state, to test the clearText         const updatedState = { text: 'Hello' };          // calling the cleatText reducer to clear the text         const action = clearText();         const newState = textReducer(updatedState, action);          // assert that the text state is now empty         expect(newState.text).toBe('');     });      // you can write more tests to test the "setText" and "clearText" reducers     // ... }); 

Output:

Screenshot-2024-04-07-at-73925-PM-min
Test Result for textReducers.test.js

Explanation:

The above code demonstrates the testing of the Redux Reducers. In order to test the reducers, we don't need to mock the redux store because the reducers functions are pure-functions and we are importing these reducers functions from the textSlice. After importing the reducer functions from the textSlice, we proceed to test two specific reducer functions:

  • The setText reducer function: The reducer function is responsible for updating the text state in the Redux store. We test it by providing an initial-state and a payload data to set. We then call the setText action creator to create an action with the payload data and pass this action to the reducer using the textReducer function. Finally, we assert that the reducer correctly updates the text state to the payload value.
  • The clearText reducer function: This reducer function clears the text state in the Redux store. We test it by providing an updated state with some text already set. We then call the clearText action creator to create an action to clear the text and pass this action to the reducer using the textReducer function. Finally, we assert that the reducer correctly clears the text state, resulting in an empty text value.

We can also write some tests to cover the edge cases for the setText and clearText reducers. By testing these reducers, we ensure that the Redux state management logic behaves as expected and correctly updates the application state in response to dispatched actions.

Conclusion

Testing a React-Redux application is crucial for ensuring the stability, maintainability and functionality of the application. By testing our components, actions, reducers and overall redux store, we can prevent potential issues. It helps us uncover bugs, verify expected behaviour, and maintain a high level of quality in our codebase. Testing empowers us to deliver a seamless user experience, enhances maintainability, and ultimately leads to a more robust and successful application. So, in conclusion, we should invest our time and effort in testing our React-Redux application thoroughly and it's worth it!



Next Article
How to Optimize the Performance of React-Redux Applications?

P

pythonpioneer
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Redux

Similar Reads

  • How to Normalize State in Redux Applications ?
    In Redux applications, efficient state management is essential for scalability and maintainability. Normalization is a technique used to restructure complex state data into a more organized format, improving performance and simplifying state manipulation. This article covers the concept of normaliza
    3 min read
  • How to Handle Errors in React Redux applications?
    To handle errors in Redux applications, use try-catch blocks in your asynchronous action creators to catch errors from API calls or other async operations. Dispatch actions to update the Redux state with error information, which can then be displayed to the user in the UI using components like error
    4 min read
  • How to Optimize the Performance of React-Redux Applications?
    Optimizing the performance of React-Redux applications involves several strategies to improve loading speed, reduce unnecessary re-renders, and enhance user experience. In this article, we implement some optimization techniques, that can significantly improve the performance of applications. We will
    9 min read
  • How to Create Store in React Redux ?
    React Redux is a JavaScript library that is used to create and maintain state in React Applications efficiently. Here React Redux solves the problem by creating a redux store that stores the state and provides methods to use the state inside any component directly or to manipulate the state in a def
    4 min read
  • How to Implement Caching in React Redux applications ?
    Caching is the practice of storing frequently used or calculated data temporarily in memory or disk. Its main purpose is to speed up access and retrieval by minimizing the need to repeatedly fetch or compute the same information. By doing so, caching helps reduce latency, conserve resources, and ult
    3 min read
  • How Redux Toolkit simplifies Redux code in React application ?
    Redux Toolkit is a powerful library designed to simplify the complexities of managing application state with Redux in React applications. At its core, Redux Toolkit provides developers with a set of utilities and abstractions that significantly reduce boilerplate code and streamline common Redux tas
    5 min read
  • How do you handle real-time updates in Redux applications?
    Handling real-time updates is essential for modern web applications to provide users with dynamic and interactive experiences. In Redux applications, managing real-time updates efficiently involves implementing strategies to synchronize the application state with changes occurring on the server in r
    5 min read
  • How to Handle Forms in Redux Applications?
    Handling forms in Redux applications involves managing form data in the Redux store and synchronizing it with the UI. By centralizing the form state in the Redux store, you can easily manage form data, handle form submissions, and maintain consistency across components. We will discuss a different a
    5 min read
  • How to handle data fetching in React-Redux Applications ?
    Data fetching in React-Redux applications is a common requirement to retrieve data from APIs or other sources and use it within your components. This article explores various approaches to handling data fetching in React-Redux applications, providing examples and explanations for each approach. Tabl
    5 min read
  • Create a weather Application using React Redux
    Weather App is a web application designed to provide real-time weather information for any location worldwide. In this article, we will make a Weather App using React and Redux. It offers a seamless and intuitive user experience, allowing users to easily access accurate weather forecasts ( temperatu
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences