Setting up your environment with Jest and React Testing Library, and configuring Babel and Parcel to work seamlessly together. 🧪

Bhavik BhuvaBhavik Bhuva
4 min read

Implementing a robust testing strategy is crucial for ensuring the reliability and maintainability of your React applications. This comprehensive guide will walk you through the various types of testing, setting up your environment with Jest and React Testing Library, and configuring Babel and Parcel to work seamlessly together.

Types of Testing in Development

Understanding the different levels of testing helps in identifying and resolving issues effectively:

• Unit Testing: Focuses on individual components or functions to ensure they work as intended in isolation.

• Integration Testing: Verifies that different modules or components interact correctly when combined.

• End-to-End (E2E) Testing: Simulates real user scenarios to test the entire application flow, from start to finish.

Setting Up Testing in Your React Application

To establish a testing environment in your React project, follow these steps:

1. Install React Testing Library: This library provides utilities to test React components in a way that resembles how users interact with your application.

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

2. Install Jest: Jest is a popular testing framework for JavaScript applications, offering a simple API and powerful features.

npm install --save-dev babel-jest @babel/core @babel/preset-env

3. Install Babel Dependencies: Babel is necessary to transpile modern JavaScript syntax for compatibility.

npm install --save-dev babel-jest @babel/core @babel/preset-env

4. Configure Babel: Create a babel.config.js file in the root of your project with the following content:

module.exports = {
  presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
};

5. Configure Parcel: Parcel performs automatic Babel transpilation, which can conflict with your custom Babel configuration. To prevent this, create a .parcelrc file at the root of your project with the following content:

{
  "extends": "@parcel/config-default",
  "transformers": {
    "*.{js,mjs,jsx,cjs,ts,tsx}": [
      "@parcel/transformer-js",
      "@parcel/transformer-react-refresh-wrap"
    ]
  }
}

6. Initialize Jest Configuration: Run the following command to set up Jest:

npx jest --init

During the setup, you’ll be prompted with several questions. Here are the recommended responses:

• Would you like to use Typescript for the configuration file? No

• Choose the test environment that will be used for testing: jsdom (browser-like)

• Do you want Jest to add coverage reports? Yes

• Which provider should be used to instrument code for coverage? babel

• Automatically clear mock calls, instances, contexts and results before every test? Yes

7. Install jest-environment-jsdom: If you’re using Jest version 28 or later, you’ll need to install this package separately:

npm install --save-dev jest-environment-jsdom

Writing Your First Test

With the setup complete, you can write your first dummy test. Create a file named sum.js with the following content:

export const sum = (a,b) => {
    return a+b;
}

all set and now lets check how to write testcases for react.

To enhance your React application’s testing setup, it’s essential to configure Babel to handle JSX syntax and install additional testing utilities. Here’s how you can proceed:

1. Install @babel/preset-react: This preset allows Babel to transpile JSX syntax.

npm install --save-dev @babel/preset-react

2. Update Babel Configuration: Modify your babel.config.js to include @babel/preset-react:

module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],
    ['@babel/preset-react', { runtime: 'automatic' }],
  ],
};

3. Install @testing-library/jest-dom: This library provides custom matchers for Jest, enhancing the readability and maintainability of your tests.

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

4. Import @testing-library/jest-dom in Your Test Files: To utilize the custom matchers, import the library at the top of your test files:

import '@testing-library/jest-dom';

5. Example Test Case: Here’s how you can write a test for a Contact component:

import React from 'react';
import { render, screen } from '@testing-library/react';
import Contact from '../../Contact';
import '@testing-library/jest-dom';

test('Should load Contact Us component', () => {
  render(<Contact />);
  const heading = screen.getByRole('heading');
  expect(heading).toBeInTheDocument();
});

By following these steps, you ensure that your testing environment is well-configured to handle React components effectively, leading to more reliable and maintainable tests.

Detailed Example:

import { render,screen} from "@testing-library/react"
import Contact from "../../Contact"
import "@testing-library/jest-dom"

// describe is just for grouping like div to maintain and ease

describe("Contact us page test cases",()=>{

    // test can also be written as "it"

it("Should load contact us component",() => {
 render(<Contact/>)
const heading =  screen.getByRole("heading")
expect(heading).toBeInTheDocument();
})

test("Should load button  component",() => {
    render(<Contact />)
//    const button =  screen.getByRole("button")
   const button =  screen.getByText("Message")
   expect(button).toBeInTheDocument(); 
   })

test("should load 2 input boxes",()=>{
     render(<Contact/>)
     // Querying
     const inputBoxes = screen.getAllByRole("textbox") // for multiple items

     // Assertion
     expect(inputBoxes.length).toBe(3)
    //  expect(inputBoxes.length).not.toBe(3)
}) 


})
0
Subscribe to my newsletter

Read articles from Bhavik Bhuva directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bhavik Bhuva
Bhavik Bhuva