DEV Community

Cover image for Jest: How to use its powerful unit tests with React
professorjrod
professorjrod

Posted on

Jest: How to use its powerful unit tests with React

Why did I learn the Jest testing library, you ask?

Well, let me tell you: it's because I'm a total jokester, and I wanted to make sure all my code was as hilarious as I am.

el risitas

Plus, with Jest, I can be confident that my code is working properly, even when I'm cracking myself up with puns and dad jokes. It's the perfect combination of function and fun-ctionality!im so sorry

Snapshot Testing


One of the coolest features of Jest is snapshot testing. This is a technique that allows you to capture the current state of a component or function and save it as a "snapshot" that you can use for later comparison.

When you run your tests again, Jest will compare the current state of the component or function to the saved snapshot and report any differences. This is an awesome way to quickly and easily catch changes in the rendering of your UI that you didn't expect.

For example, suppose you have a simple React component that displays a list of items:

import React from 'react';

const List = ({ items }) => {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};

export default List;
Enter fullscreen mode Exit fullscreen mode

To test this component with Jest, you can use a snapshot test like this:

import React from 'react';
import { render } from '@testing-library/react';
import List from './List';

test('List component renders items correctly', () => {
  const items = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' },
    { id: 3, name: 'Item 3' },
  ];

  const { container } = render(<List items={items} />);

  // Take a snapshot of the rendered component and save it to a file.
  // The snapshot file will be stored in a __snapshots__ directory
  // next to the test file.
  expect(container).toMatchSnapshot();
});
Enter fullscreen mode Exit fullscreen mode

In this test, we use Jest's render function from the @testing-library/react package to render the List component and capture its output. We then use Jest's toMatchSnapshot matcher to take a snapshot of the rendered component and save it to a file. The first time you run this test, Jest will create the snapshot file and save it in a snapshots directory next to the test file.

If you run the test again, Jest will compare the current output of the component to the saved snapshot and report any differences. For example, if you change the List component to display the items in reverse order:

import React from 'react';

const List = ({ items }) => {
  return (
    <ul>
      {items.reverse().map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};

export default List;

Enter fullscreen mode Exit fullscreen mode

When you run the tests again, Jest will detect the change in the output of the component and report a failure:

FAIL  src/__
Enter fullscreen mode Exit fullscreen mode

Sweet... Failure!

Mocking


nelson

Mocking is a technique in software testing that involves replacing the dependencies of a unit under test with fake objects, so that the behavior of the unit under test can be controlled and the output can be predicted.

In the case of Jest, mocking can be used to stub the behavior of certain functions, allowing you to control the output of those functions in your tests. This can be a useful tool for isolating units of code and testing their behavior in a controlled way.

// myModule.js
export const myFunction = (x) => {
  // some complex logic...
  return x + 1;
}

// myModule.test.js
import { myFunction } from './myModule';

jest.mock('./myModule');

test('myFunction adds one to the input', () => {
  // Replace the implementation of myFunction with a fake that always
  // returns 5.
  myFunction.mockImplementation(() => 5);

  // Now, when we call myFunction in our test, it will always return 5
  // regardless of the input.
  expect(myFunction(2)).toBe(5);
  expect(myFunction(10)).toBe(5);
  expect(myFunction(-5)).toBe(5);
});
Enter fullscreen mode Exit fullscreen mode

In this example, we use Jest's mockImplementation function to replace the implementation of myFunction with a fake that always returns the same value. This allows us to test the behavior of our code that depends on myFunction without having to worry about the complex logic inside myFunction itself.

Mocking can be a powerful tool for testing, but it should be used with caution. Overuse of mocking can lead to tests that are fragile and difficult to understand, so it's important to strike a balance when using this technique in your tests.

In conclusion


Jest is a powerful and easy-to-use JavaScript testing framework that can help you write effective and reliable tests for your code.

With features like snapshot testing, mocking, and code coverage, Jest has everything you need to confidently build and deploy your JavaScript applications. So, give Jest a try and HAPPY CODING!!!!

Top comments (0)