Skip to main content

Create Test Case using Jest library in React JS

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.


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;



Now, we can write three types of test cases for that
1. Valid Input and Submission Test Case
2. Invalid Input and Submission Test Case
3. Empty Fields Test Case

before that, 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: first need to Create the
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: 'user' } });
  fireEvent.change(screen.getByPlaceholderText('Password'),
     { target: { value: 'password' } });
  fireEvent.click(screen.getByText('Submit'));

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



2. Invalid Input and Submission Test Case: create the new file 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. Fields Test Case: create the new file 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();
  });
 

Now you just need to execute the cmd

npm test

see the result



Thanks for referring to this article, hope it will help
 







Comments

Popular posts from this blog

Interview Questions of SPFx SharePoint

What is SPFx? The SharePoint Framework (SPFx) is a web part model that provides full support for client-side SharePoint development, it is easy to integrate with SharePoint data, and extend Microsoft Teams. With the SharePoint Framework, you can use modern web technologies and tools in your preferred development environment to build productive experiences and apps that are responsive and mobile-ready. Scenario Based asking Scenario 1: Scenario: Your team is developing a SharePoint Framework (SPFx) web part that needs to retrieve data from an external API and display it on a SharePoint site. The API requires authentication using OAuth 2.0. The web part should also allow users to refresh the data manually. Question 1: How would you approach implementing this functionality in an SPFx web

Interview Question of Advanced SharePoint SPFx

1. What is WebPack? A module bundling system built on top of Node. js framework is known as a WebPack. It is capable to handle the combination and minification of JavaScript and CSS files, also other files such as images by using plugins. WebPack is the recommended way of bundling the files in JS framework and .Net frameworks. In the SPFx it is used with React Js. 2. What is PowerShell.? PowerShell is a platform introduced by Microsoft to perform cross-platform task automation and configuration management framework, it is made up of a command-line shell, a scripting language. it can be run on Windows, Linux, and macOS. 3. What is bundling and Minification? The terms bundling and minification are the processes of code compressing, which is used to improve the load and request time, It is used in modern JavaScript frameworks and .Net frameworks. It improves the load time by reducing the number of requests to the s

Top20 - SharePoint Framework (SPFx) Interview Questions

1.  Which tool we can use to generate a SharePoint Framework (SPFx) solution? Developers can use  Yeoman to generate SharePoint Framework (SPFx) solution, it is a client-side scaffolding open-source tool to help in web-based development. 2. How developer can ensure that the solution deployed was immediately available to all site collections in SPFx?  To ensure the availability of the deployed solution on all the site collections developer has to configure  skipFeatureDeployment: true  in package-solution.json {     "solution" : {       "name" : "theultimateresources-deployment-client-side-solution" ,       "id" : "as3feca4-4j89-47f1-a0e2-78de8890e5hy" ,       "version" : "2.0.0.0" ,       "skipFeatureDeployment" : true     },     "paths" : {       "zippedPackage" : "solution/theultimateresources-deploy-true.sppkg"     }  }