This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Test React Typescript Component with Jest and RTL

  • ReactJS
  • December 3, 2023

Share On :

Introduction

Unit testing React components with TypeScript is a common practice to ensure the correctness of your components, especially when TypeScript is used in a React project. The process is quite similar to unit testing in JavaScript, but with some adjustments to accommodate TypeScript’s type system.

There are two popular testing libraries for React: Enzyme and React Testing Library.

In this guide we will be testing React components using React Testing Library and Jest. As RTL provides a simple and straightforward way to test components that promotes good test practices and Jest will take care of running tests and handling assertions.

We’ll walk through setting up your project, creating a simple registration form, and writing test cases for it.

Project Setup

Create a TypeScript and React module with Liferay:

Follow our blog post on TypeScript and React with Liferay to set up your module.

When you create a react app, you have some testing dependencies by default installed in your package.json. Make sure you have the following dependencies installed in your project:

 @types/jest @testing-library/react @testing-library/jest-dom  npm i @testing-library/user-event

Install additional dependencies:

[ npm install jest ts-jest  jest-config jest-environment-jsdom ]

Configure Jest:

Run the following command to create a jest.config.json file:

[ npx jest –init ]

This will generate a jest.config.json file with default configurations. It includes mappings for module names and mocks. Additionally, it specifies the file extensions to be considered and sets the test environment to jsdom. Make sure your project structure and paths align with the configured mappings for the best results.

Initializing Jest Configuration

Update tsconfig.json:

Add the Jest type to the compilerOptions:

[ “types”: “node”, “jest” ]

Adding Jest Type to CompilerOptions

Create tsconfig.test.json:

Create a tsconfig.test.json file with the following configuration:

				
					{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "jsx": "react-jsx",
    "esModuleInterop": true
  }
}



				
			

Creating a Registration Form Component

Now that your project is set up, let’s create a simple registration form and write test cases for it and export default RegisterForm.

				
					import React from "react";
import {
  Grid,
  makeStyles,
  Card,
  CardContent,
  CardActions,
  Button,
  CardHeader,
} from "@material-ui/core";

import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
import { TextField } from "formik-material-ui";

interface Values {
  firstName: string;
  lastName: string;
  city: string;
  email: string;
  password: string;
}

const useStyles = makeStyles((theme: any) => ({
  padding: { padding: theme.spacing(3) },
  button: { margin: theme.spacing(1) },
}));

const lowercaseRegEx = /(?=.*[a-z])/;
const uppercaseRegEx = /(?=.*[A-Z])/;
const numericRegEx = /(?=.*[0-9])/;
const lengthRegEx = /(?=.{6,})/;

const validationSchema = Yup.object().shape({
  firstName: Yup.string().required("Required"),
  lastName: Yup.string().required("Required"),
  email: Yup.string().email("Invalid email").required("Required"),
  password: Yup.string()
    .matches(
      lowercaseRegEx,
      "Must contain one lowercase alphabetical character!"
    )
    .matches(
      uppercaseRegEx,
      "Must contain one uppercase alphabetical character!"
    )
    .matches(numericRegEx, "Must contain one numeric character!")
    .matches(lengthRegEx, "Must contain 6 characters!")
    .required("Required!"),
});

const RegisterForm: React.FC = () => {
  const classes = useStyles();

  const onSubmit = (values: Values) => {
    console.log(values);
  };

  return (
    <Grid container justifyContent="center" spacing={1}>
      <Grid item md={6}>
        <Card className={classes.padding}>
          <CardHeader title="REGISTER FORM"></CardHeader>
          <Formik
            initialValues={{
              firstName: "",
              lastName: "",
              city: "",
              email: "",
              password: "",
            }}
            validationSchema={validationSchema}
            onSubmit={onSubmit}
          >
            {({ dirty, isValid, values, handleChange, handleBlur }) => {
              return (
                <Form>
                  <CardContent>
                    <Grid item container spacing={1} justifyContent="center">
                      <Grid item xs={12}>
                        <Field
                          label="First Name"
                          variant="outlined"
                          fullWidth
                          name="firstName"
                          value={values.firstName}
                          component={TextField}
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <Field
                          label="Last Name"
                          variant="outlined"
                          fullWidth
                          name="lastName"
                          value={values.lastName}
                          component={TextField}
                        />
                      </Grid>

                      <Grid item xs={12}>
                        <Field
                          label="City"
                          variant="outlined"
                          fullWidth
                          name="city"
                          value={values.city}
                          component={TextField}
                        />
                      </Grid>

                      <Grid item xs={12}>
                        <Field
                          label="Email"
                          variant="outlined"
                          fullWidth
                          name="email"
                          value={values.email}
                          component={TextField}
                        />
                      </Grid>
                      <Grid item xs={12} >
                        <Field
                          label="Password"
                          variant="outlined"
                          fullWidth
                          name="password"
                          value={values.password}
                          type="password"
                          component={TextField}
                        />
                      </Grid>
                    </Grid>
                  </CardContent>
                  <CardActions>
                    <Button
                      disabled={!dirty || !isValid}
                      variant="contained"
                      color="primary"
                      type="submit"
                      className={classes.button}
                    >
                      REGISTER
                    </Button>
                  </CardActions>
                </Form>
              );
            }}
          </Formik>
        </Card>
      </Grid>
    </Grid>
  );
};





				
			
Writing Test Cases

Folder Structure

Create a __tests__ folder inside your component folder for test files.

Creating Test Folder for Component

The use of a special folder name like “__tests__”  signifies that the content of this folder is related to testing. This can be beneficial when someone new joins a project or when revisiting the code after some time. However, it’s important to note that the use of “__tests__” is a convention and not a strict rule. In Jest, the “__tests__” convention is recognized by default, but Jest is flexible enough to work with other configurations or file structures if needed. Always refer to the documentation of the testing framework you are using to understand its conventions and customization options. 

Writing Unit Tests

Create Formtable.test.tsx file inside the __ tests__ folder for writing test cases for react code.Here, we will create a unit test for that Form.tsx component. First of all, make sure we have created Form.test.tsx on /components/__test__/Form.test.tsx.

				
					
import { render, screen, fireEvent, act } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import RegisterForm from "../components/Form";

describe("RegisterForm component", () => {
  test("can fill out the form and submit", async () => {
    render(<RegisterForm />);

    await act(async () => {
      const firstNameInput = screen.getByLabelText("First Name");
       const lastNameInput = screen.getByLabelText("Last Name");
      const cityInput = screen.getByLabelText("City");
      const emailInput = screen.getByLabelText("Email");
      const passwordInput = screen.getByLabelText("Password");
      const registerButton = screen.getByText("REGISTER");

      userEvent.type(firstNameInput, "John");
      userEvent.type(lastNameInput, "Doe");
      userEvent.type(cityInput, "Sample City");
      userEvent.type(emailInput, "john.doe@example.com");
      userEvent.type(passwordInput, "Password123");

      fireEvent.click(registerButton);
    });
  });

  test("displays validation error for invalid email", async () => {
    render(<RegisterForm />);

 await act(async () => {
      const emailInput = screen.getByLabelText("Email");
      const registerButton = screen.getByText("REGISTER");

      userEvent.type(emailInput, "invalidemail");
      fireEvent.click(registerButton);
    });

    // Add assertion to check for the expected error message
expect(screen.getByText("Invalid email")).toBeInTheDocument();
  });
});




				
			

 Explanation:

  • The render(<RegisterForm />) function is used to render the RegisterForm component.
  • The act function from @testing-library/react is used to handle asynchronous actions. In this case, it wraps the code that interacts with the form elements.
  • screen.getByLabelText and screen.getByText are used to obtain references to form elements by their associated labels or text.
  • userEvent.type is used to simulate typing input into form fields.
  • fireEvent.click simulates clicking the “REGISTER” button.
  • The test checks if the form can be filled out and submitted successfully.
Running Tests

Execute the following command to run your tests:

[ npm test ]

Running Tests Components

Addressing Issues

If you encounter warnings or errors, ensure you use await with act and fix any selector mismatches.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

May 27, 2019
Liferay with React Cover Image
Liferay React Portlet
July 19, 2023
React with Liferay cover Image
React with Liferay
November 10, 2023
typescript and react with liferay cover image
TypeScript and React with Liferay
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform User-Friendly, Secure and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 6, 2023
Dynamic E-commerce Platform_for Sales, Rentals and Inventory Management
Dynamic E-commerce Platform for sales, Rentals and Inventory Management
October 3, 2023
Simplify Approvals and Goals With Agenda & Meeting SaaS Platform
Simplify Approvals and Goals With Agenda & Meeting SaaS Platform

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram