✨It's 2025, But Jest🔧 is Still Rocking the Testing World 🚀
Jagroop Singh

Jagroop Singh @jagroop2001

About: 👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views

Location:
India
Joined:
Apr 5, 2022

✨It's 2025, But Jest🔧 is Still Rocking the Testing World 🚀

Publish Date: Feb 9
18 7

Testing your React components might sound intimidating, but with Jest, it’s actually fun! 🚀

In the era of AI, many people believe that Unit Testing is dead or no longer necessary. 🚫🤖 But let me tell you—it's one of the most underrated skills in software development! 💡✨

While most developers tend to skip it, thinking it's not essential, Unit Testing is actually a secret weapon 🛡️ that can elevate your code quality and save countless hours of debugging. 🐛⏱️

In fact, I believe that learning Unit Testing is far more important than jumping on the bandwagon of the next shiny framework. 🚀📚

Mastering this skill will not only make your codebase more reliable but also make you a better developer. 💻✅

In this blog, I'll dive into Jest for unit testing React components.Let’s get our hands dirty! 💪


🔹 Why Jest?

Before we jump in, why should you even care about Jest?

Jest is a delightful JavaScript testing framework created by Facebook. It’s fast, easy to set up, and works seamlessly with React.
Plus, it comes with built-in support for mocking, assertions, and code coverage. 🛠️

Alright, enough chit-chat. Let’s code! 💪


📦 Setting Up Jest

  1. Create React App (already comes with Jest):
   npx create-react-app my-app
   cd my-app
   npm test
Enter fullscreen mode Exit fullscreen mode

Boom! Jest is running. 🚀 But this method is deprecated so we can use other module bundler like Vite, Webpack etc. and setup jest manually.

  1. Manual Setup:
   npm install --save-dev jest @testing-library/react @testing-library/jest-dom
Enter fullscreen mode Exit fullscreen mode

🔧 Writing Your First Test

Let’s create a simple component and test it!

Counter.js

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h1 data-testid="count">{count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

📖 Counter.test.js

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

test('renders initial count', () => {
  render(<Counter />);
  const countElement = screen.getByTestId('count');
  expect(countElement).toHaveTextContent('0');
});

test('increments count on button click', () => {
  render(<Counter />);
  const buttonElement = screen.getByText('Increment');
  fireEvent.click(buttonElement);
  const countElement = screen.getByTestId('count');
  expect(countElement).toHaveTextContent('1');
});
Enter fullscreen mode Exit fullscreen mode

🚀 Run Tests

npm run test
Enter fullscreen mode Exit fullscreen mode

You should see green checkmarks! 😃🔹

intro unit test


📊 Snapshot Testing

Want to make sure your UI doesn’t change unexpectedly? Use snapshots! 📸

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


test('matches snapshot', () => {
    const { asFragment } = render(<Counter />);
    expect(asFragment()).toMatchSnapshot();
  });

Enter fullscreen mode Exit fullscreen mode

snapshot unit testing

Run the test, and Jest will create a snapshot file. Next time you run tests, it will compare the current UI to the saved snapshot.


🔐 Mocking Functions

Sometimes, you need to mock functions to isolate your component's behavior.

Greeting.js

import React, { useEffect, useState } from 'react';

const Greeting = ({ fetchGreeting }) => {
    const [greeting, setGreeting] = useState('');

    useEffect(() => {
      fetchGreeting().then(setGreeting);
    }, [fetchGreeting]);

    return <h1>{greeting}</h1>;
  };

  export default Greeting;
Enter fullscreen mode Exit fullscreen mode

Greeting.test.js

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

test('renders greeting from API', async () => {
  const mockFetchGreeting = jest.fn().mockResolvedValue('Hello, Jest!');
  render(<Greeting fetchGreeting={mockFetchGreeting} />);

  const greetingElement = await screen.findByText('Hello, Jest!');
  expect(greetingElement).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

mocking unit tests


🚀 Tips for Better Testing

  • Test Behavior, Not Implementation: Focus on what the component does, not how it does it.
  • Keep Tests Isolated: Don’t let tests depend on each other.
  • Use beforeEach for Repeated Setup: Clean and DRY code! 💡

🎓 Your Challenge!

Now it’s your turn! 🚀 Create a TodoList component with the following features:

  1. Display a list of tasks.
  2. Add new tasks.
  3. Mark tasks as completed.

For code you can take reference from this blog of mine:

Challenge: Write unit tests for each feature! Share your code in the comments 🚀✨


Happy Testing! 💡🌟 Let me know how your testing journey goes! 🚀

Comments 7 total

  • caga
    cagaFeb 9, 2025

    Your blogs makes complicated stuffs to easy to understand concepts about new things. I really understand each and every part of this blog. I will try this on Todo List App.

  • Paul Loveridge
    Paul LoveridgeFeb 9, 2025

    Unit testing is the secret ingredient to good code.

    So many time it's tempting to skip it to save time. "I know it works" , "It's just a prototype" whatever your usual excuse is . Dont skip your unit tests

    If you keep writing tests along side your code you'll hit moments when it suddently catches a failure or bug you didn't spot.

    Unit testing doesn't slow down development - it speeds it up.

    Oh, top tip - get IDE extension like the test runners in VSCode that can auto run your tests for you. It's awesome seeing red checks turn green before your eyes.

    • Jagroop Singh
      Jagroop SinghFeb 10, 2025

      @drstrangelug , Writing unit tests not only catches hidden bugs early but also boosts long-term development speed and confidence. 🚀

  • Florian Rappl
    Florian RapplFeb 9, 2025

    Migrated all my projects from Jest to Vitest. Much faster, much better support for modern codebases - much easier to configure.

    • Jagroop Singh
      Jagroop SinghFeb 10, 2025

      sounds interesting !!
      let me try Vitest.

      • AI_Dosage
        AI_DosageFeb 20, 2025

        Started using it on a new project. It's amazing

Add comment