Skip to main content

Create Test Case using Jest library in React JS

Creating Unit Test Cases in React JS with Jest and React Testing Library

Creating Unit Test Cases in React JS with Jest and React Testing Library

In this article, you will get an understanding of how we can create a basic unit test case in React JS.

Creating automated test cases for a React application involves using testing libraries and frameworks like Jest and React Testing Library. For testing a LoginForm component, you would want to cover different scenarios like valid and invalid inputs, form submission, error handling, and more. Below, I'll provide an example of how to create test cases using Jest and React Testing Library.

LoginForm Component

Let's assume your LoginForm component looks something like this:


import React, { useState } from 'react';

const LoginForm = ({ onLogin }) => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');

    const handleEmailChange = (event) => {
        setEmail(event.target.value);
    };

    const handlePasswordChange = (event) => {
        setPassword(event.target.value);
    };

    const handleSubmit = (event) => {
        event.preventDefault();

        // Basic validation
        if (!email.includes('@')) {
            setError('Invalid email address');
            return;
        }

        // Simulate login
        if (email === '[email protected]' && password === 'password123') {
            onLogin();
        } else {
            setError('Invalid credentials');
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <div>
                <label htmlFor="email">Email</label>
                <input
                    type="email"
                    id="email"
                    value={email}
                    placeholder="Email"
                    onChange={handleEmailChange}
                />
            </div>
            <div>
                <label htmlFor="password">Password</label>
                <input
                    type="password"
                    id="password"
                    value={password}
                    placeholder="Password"
                    onChange={handlePasswordChange}
                />
            </div>
            {error && <div>{error}</div>}
            <button type="submit">Submit</button>
        </form>
    );
};

export default LoginForm;
    

Test Cases for LoginForm

Now, we can write three types of test cases for the LoginForm component:

  1. Valid Input and Submission Test Case
  2. Invalid Input and Submission Test Case
  3. Empty Fields Test Case

Before writing the test cases, execute this command to install the required dependencies:


npm install --save-dev jest @testing-library/react @testing-library/jest-dom
    

1. Valid Input and Submission Test Case

Create a new file named buttonValidInput.test.js:


import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import LoginForm from '../loginForm';

test('valid input and submission', () => {
    render(<LoginForm />);

    fireEvent.change(screen.getByPlaceholderText('Email'), {
        target: { value: '[email protected]' },
    });
    fireEvent.change(screen.getByPlaceholderText('Password'), {
        target: { value: 'password123' },
    });
    fireEvent.click(screen.getByText('Submit'));

    expect(screen.queryByText('Invalid credentials')).toBeNull();
});
    

2. Invalid Input and Submission Test Case

Create a new file named buttonInValidInput.test.js:


import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import LoginForm from '../loginForm';

test('invalid input and submission', () => {
    render(<LoginForm />);

    fireEvent.change(screen.getByPlaceholderText('Email'), {
        target: { value: 'invaliduser' },
    });
    fireEvent.change(screen.getByPlaceholderText('Password'), {
        target: { value: 'wrongpassword' },
    });
    fireEvent.click(screen.getByText('Submit'));

    expect(screen.getByText('Invalid email address')).toBeInTheDocument();
});
    

3. Empty Fields Test Case

Create a new file named buttonEmptyInput.test.js:


import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import LoginForm from '../loginForm';

test('empty fields submission', () => {
    render(<LoginForm />);

    fireEvent.click(screen.getByText('Submit'));

    expect(screen.getByText('Invalid email address')).toBeInTheDocument();
});
    

Running the Tests

Now, you just need to execute the following command to run the tests:


npm test
    

You should see the test results in your terminal.

Conclusion

By following the steps above, you can create basic unit test cases for your React components using Jest and React Testing Library. Testing ensures that your application behaves as expected and helps catch bugs early in the development process. Whether you're testing valid inputs, invalid inputs, or empty fields, these test cases will help you build a robust and reliable application.

Thanks for referring to this article. Hope it helps!

Comments

Popular posts from this blog

Power Apps modern driven app Interview Question and answer

Power Apps Modern Driven App: Questions and Answers Power Apps Modern Driven App: Questions and Answers Power Apps modern driven apps are low-code/no-code platforms that enable users to create custom applications. Below are some common questions and detailed answers to help you understand their capabilities and applications. Question 1: What is a Power Apps modern driven app? Answer: A Power Apps modern driven app is a low-code/no-code application development platform provided by Microsoft. It allows users to create custom applications that can run on various devices and platforms without extensive coding. These apps are built using a visual interface and can integrate with different data sources. Question 2: What are the key components of a Power Apps modern driven app? Answer: The key components of a Power Apps modern driven app are: Screens: Serve as the user interface for the app, including layouts, ...

SPFX Interview question for 2023

SPFx Interview Questions for 2023 SPFx Interview Questions for 2023 Author: Vishal Thakur Question 1: What is SharePoint Framework (SPFx)? Answer: SharePoint Framework (SPFx) is a development model introduced by Microsoft for creating client-side web parts and extensions for SharePoint Online and SharePoint 2019. It is based on modern web technologies like JavaScript, TypeScript, and React, providing a rich and responsive user experience. Question 2: What are the key advantages of using SPFx for SharePoint development? Answer: SPFx offers several advantages, such as: Responsive and mobile-ready web parts and extensions. Seamless integration with SharePoint data and services. Support for modern web development practices and tools. Easy deployment and hosting options. Enhanced security and isolation through the SharePoint app model. Question 3: Can you explain ...

Create self signed SSL certificate

How to Create a Self-Signed SSL Certificate for React JS Using mkcert How to Create a Self-Signed SSL Certificate for React JS Using mkcert A self-signed certificate is a digital certificate that is created and signed by the same entity it identifies. Unlike certificates issued by trusted Certificate Authorities (CAs), self-signed certificates aren't verified by external parties. They're commonly used for local development, testing, or internal systems where the identity verification provided by a CA is not necessary. Although self-signed certificates can secure communication, they lack the third-party validation provided by CA-signed certificates, and users may encounter browser warnings when accessing websites using self-signed certificates. In this guide, we’ll walk you through the steps to create a self-signed SSL certificate for your React JS application using mkcert . Step 1: Install Chocolatey ...