Open In App

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.

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

Similar Reads