Revolutionize your React Unit Testing: Exploring ChatGPT's Capabilities

Written on 2023-05-08 by Adam Drake - 5 min read

Image of Revolutionize your React Unit Testing: Exploring ChatGPT's Capabilities

Unit tests are an essential component of any frontend application, as they function as the first line of defence in detecting potential errors, ensuring the system's stability, and preserving code integrity. With the dynamic nature of frontend technologies, the complexity of user interfaces and interactions, and the multitude of devices, browsers, and platforms on which applications are expected to run, developers face a seemingly endless array of scenarios that may lead to unforeseen issues. Without rigorous unit tests in place, these problems could easily slip through the cracks, compromising not only the intended user experience but also tarnishing the credibility of the application and the organization behind it.

Frontend developers opinions on Unit tests are wide ranging and often can lead to heated discussions... See this interesting discussion between The Primeagen and Theo. I can personally see both sides of the argument on this one.

Unit tests are an essential component of any frontend application, as they function as the first line of defence in detecting potential errors, ensuring the system's stability, and preserving code integrity.

There are many things to consider with tests, such as the type of app you are building, who and how big the audience is, whats the business strategy etc... but I can testify that unit tests have saved my butt more than a few times so I think they are well worth while.

But writing unit tests suck!

Having said the above though, you may be surprised that I never actually looked forward to writing unit tests. I saw them as something that would help me build a more robust app but I am not totally enamoured with the actual writing of tests. It's like going to school, I knew it would help me in the future but I didn't love the process when I was there.

Until recently this has always been an internal struggle within me. Resolving internal conflicts (and wasting much energy in doing do) so I finally can focus enough energy in one direction to write some actual tests.

It's like going to school, I knew it would help me in the future but I didn't love the process when I was there.

Writing tests sometimes can be relatively easy but it also requires you to take a step back and think through all the potential scenarios in which this particular piece of code could be used. Which isn't easy! When you write code you write it with a BIG ASSUMPTION that it will be used in a certain way. However, as soon as your app is out in the big wide world and you have real people (who do some really weird stuff sometimes) actually using it then scenarios can pop up that you would never think of.

ChatGPT to the rescue (again)

So how does one get over this procrastination bump of writing an actual test? Well, the same way many issues seem to be solved these days. By using AI!

ChatGPT is remarkably good (at least in my experience) in writing unit tests. And this makes sense. Unit tests are by their very definition:

A unit test is a type of software testing where individual components or functions of a program are tested in isolation to ensure they perform correctly. The goal is to validate that each unit of the code operates as expected, identify bugs, and enhance code reliability and maintainability.

This means ChatGPT (usually) doesn't need any further context outside of the code you give it. You can literally write:

Write me a unit test for this React Component:

And it does it for you. It's like a dream junior colleague you always wanted!

Example

So let me give you a little example of what I have tried in the past:

Write a unit test for this react component:

export const StatusIcon = ({ isCompleted, size }: StatusIconProps) => {
  return (
    <>
      {isCompleted ? (
        <ThemeIcon color="#66C0A7" size={size || 22} radius="xl">
          <IconCheck size="1rem" />
        </ThemeIcon>
      ) : (
        <ThemeIcon color="gray" size={size || 22} radius="xl">
          <IconCircleDot size="1rem" />
        </ThemeIcon>
      )}
    </>
  );
};

And this is what it came back with:

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

describe('StatusIcon', () => {
  it('should render a completed icon when isCompleted is true', () => {
    const { getByTestId } = render(<StatusIcon isCompleted={true} />);

    expect(getByTestId('completed-icon')).toBeInTheDocument();
  });

  it('should render an uncompleted icon when isCompleted is false', () => {
    const { getByTestId } = render(<StatusIcon isCompleted={false} />);

    expect(getByTestId('uncompleted-icon')).toBeInTheDocument();
  });

  it('should render an icon with the specified size', () => {
    const size = 28;
    const { getByTestId } = render(<StatusIcon isCompleted={true} size={size} />);

    const icon = getByTestId('completed-icon');
    expect(icon).toBeInTheDocument();
    expect(icon).toHaveStyle(`width: ${size}px`);
    expect(icon).toHaveStyle(`height: ${size}px`);
  });
});

Now to be fair I had to do a few tweaks to get the test exactly as I wanted it but it give me a hell of a good initial test to work with and iterate on.

Conclusion

If you can build your app alongside tests (unit, integration and End-to-End) then you are giving yourself a better chance of not introducing bugs to your app and ensuring your users have a smooth experience on your app. Obviously, like anything in this world, this is not guaranteed but it's always good to put the odds in your favour.

But writing tests takes time, cognitive load and effort that could be otherwise spent elsewhere on potentially more exciting things. It's always a trade off. By using these new emerging tools such as ChatGPT to help in this effort means you are more likely to include tests in your app where you once did not and this is a good think in my opinion.

Loading...

Adam Drake AI Selfie

Written by Adam Drake

Adam Drake is a Frontend React Developer who is very passionate about the quality of the web. He lives with his wife and three children in Prague in the Czech Republic.

Adam Drakes Site © 2024