DEV Community

Cover image for ✨It's 2025, But JestπŸ”§ is Still Rocking the Testing World πŸš€
Jagroop Singh
Jagroop Singh

Posted on

✨It's 2025, But JestπŸ”§ is Still Rocking the Testing World πŸš€

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! πŸš€

Top comments (6)

Collapse
 
drstrangelug profile image
Paul Loveridge • Edited

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.

Collapse
 
jagroop2001 profile image
Jagroop Singh

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

Collapse
 
florianrappl profile image
Florian Rappl

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

Collapse
 
jagroop2001 profile image
Jagroop Singh

sounds interesting !!
let me try Vitest.

Collapse
 
paxnw profile image
caga

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.

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @paxnw