How ChatGPT Helps with Code Documentation and Unit Testing

Learn how AI language model ChatGPT can help you streamline code documentation, write better unit tests, and create user-friendly documentation.

How ChatGPT Helps with Code Documentation and Unit Testing

How many times have you been focused on programming and forgetting to write the very simple code documentation of your functions, methods, and classes? I'm not asking about unit tests 🤷🏻‍♂️.

This happened often to me until I found out ChatGPT can do it.

Besides code documentation, it does a good job of writing the unit tests. Moreover, at the end, I can ask him to generate user-friendly documentation for other contributors who would want to use my code.

In this article, I'll show you how to use ChatGPT to write:

Let machine learning make software development and our software developers' lives easier.

How ChatGPT Helps with Code Documentation

As simple as it sounds, just ask him.

To show this in action, we actually need a code example, I was lazy and asked ChatGPT to write it for us.

Here's the javascript code it written:

// This code generates a random number between 1 and 10
function getRandomNumber() {
  return Math.floor(Math.random() * 10) + 1;
}

// This function checks if a number is even
function isEven(number) {
  return number % 2 === 0;
}

// This function doubles a number
function doubleNumber(number) {
  return number * 2;
}

// This function logs the result of doubling a random even number
function logDoubleOfRandomEven() {
  const randomNumber = getRandomNumber();
  if (isEven(randomNumber)) {
    const doubledNumber = doubleNumber(randomNumber);
    console.log(`The double of ${randomNumber} is ${doubledNumber}`);
  } else {
    console.log(`${randomNumber} is not even. Cannot double it.`);
  }
}

// Call the function to log the result of doubling a random even number
logDoubleOfRandomEven();

Some very simple functions with little code documentation for us to understand what's going on.

Huh, the hard part is done! Let's get to the fun part! We can open the ChatGPT chat and order him very nicely:

Add jsDoc for this code and make sure you include code tags

Include the code you want, as shown in the screenshot below, and leave some spaces below to do so.

Add jsDoc ChatGPT prompt
Add jsDoc ChatGPT prompt
💡
I used make sure you include code tags because it sometimes returns the code in paragraphs, so this tells him to include the code in a code block.

Have you tried it? Here're my results:

/**
 * Generates a random number between 1 and 10.
 *
 * @returns {number} A random number between 1 and 10.
 */
function getRandomNumber() {
  return Math.floor(Math.random() * 10) + 1;
}

/**
 * Checks if a number is even.
 *
 * @param {number} number - The number to check.
 * @returns {boolean} true if the number is even, false otherwise.
 */
function isEven(number) {
  return number % 2 === 0;
}

/**
 * Doubles a number.
 *
 * @param {number} number - The number to double.
 * @returns {number} The double of the input number.
 */
function doubleNumber(number) {
  return number * 2;
}

/**
 * Logs the result of doubling a random even number.
 */
function logDoubleOfRandomEven() {
  const randomNumber = getRandomNumber();
  if (isEven(randomNumber)) {
    const doubledNumber = doubleNumber(randomNumber);
    console.log(`The double of ${randomNumber} is ${doubledNumber}`);
  } else {
    console.log(`${randomNumber} is not even. Cannot double it.`);
  }
}

// Call the function to log the result of doubling a random even number
logDoubleOfRandomEven();

Now you don't have an excuse to not have your code written as a guru would!

Pretty good, huh?

Writing Better Unit Tests with ChatGPT

Now, once we have documented our code, it's time to improve code quality even more and add some unit tests.

We go again to chat, and ask chatgpt to:

Write unit tests using jest

You don't need to include the code anymore, it's smart enough to understand it must write the unit tests for previous code. Just make sure you keep asking it in the same chat room, always!

Here are our awesome unit tests:

const {
  getRandomNumber,
  isEven,
  doubleNumber,
  logDoubleOfRandomEven,
} = require('./example');

describe('getRandomNumber', () => {
  test('should generate a number between 1 and 10', () => {
    const randomNumber = getRandomNumber();
    expect(randomNumber).toBeGreaterThanOrEqual(1);
    expect(randomNumber).toBeLessThanOrEqual(10);
  });
});

describe('isEven', () => {
  test('should return true for an even number', () => {
    const evenNumber = 2;
    expect(isEven(evenNumber)).toBe(true);
  });

  test('should return false for an odd number', () => {
    const oddNumber = 3;
    expect(isEven(oddNumber)).toBe(false);
  });
});

describe('doubleNumber', () => {
  test('should double a number', () => {
    const number = 3;
    expect(doubleNumber(number)).toBe(6);
  });
});

describe('logDoubleOfRandomEven', () => {
  test('should log the double of a random even number', () => {
    const consoleSpy = jest.spyOn(console, 'log');
    const mockedRandomNumber = 4;
    const expectedOutput = `The double of ${mockedRandomNumber} is ${doubleNumber(mockedRandomNumber)}`;
    jest.spyOn(global.Math, 'random').mockReturnValueOnce(mockedRandomNumber / 10);
    logDoubleOfRandomEven();
    expect(consoleSpy).toHaveBeenCalledWith(expectedOutput);
    consoleSpy.mockRestore();
  });

  test('should log an error message if the random number generated is not even', () => {
    const consoleSpy = jest.spyOn(console, 'log');
    const mockedRandomNumber = 3;
    const expectedOutput = `${mockedRandomNumber} is not even. Cannot double it.`;
    jest.spyOn(global.Math, 'random').mockReturnValueOnce(mockedRandomNumber / 10);
    logDoubleOfRandomEven();
    expect(consoleSpy).toHaveBeenCalledWith(expectedOutput);
    consoleSpy.mockRestore();
  });
});

Don't rely on it entirely, this code can be broken sometimes, Just take it, run it, and if it's fine, good, if not refactor it or even ask him again:

These unit tests are not right, recheck them

It'll provide the unit tests you need, for sure!

Creating User-Friendly Documentation with ChatGPT

It's time to share our code with our fellas!

We go back to the chat and ask it to:

Write user-friendly documentation and provide some examples of how to use the code

It already knows for what code you need the documentation if you keep asking him in the same chat room.

The generated documentation is too long to include here, so I'll split it into some small parts. What I really like about chatgpt, is how it manages to organize the headers and code examples.

This is how it started, with a small introduction:

Later, it went to the usage:

Of course, it doesn't know how you going to export it as well as the name of the file, so it just did guess. You need to provide more info for it if you want more precise documentation.

As you might guess, it thinks this javascript code will be running on nodejs environment, and provided the input and output:

Mark how good are the descriptions and how good it can explain what's going on with your code.

Finally the code examples!

Example 1: Generate and Double a Random Even Number

Example 2: Generate a Random Number

Example 3: Check if a Number is Even

And example 4: Double a Number

Impressive, right? Think about it, how much time have we saved? In less than 10 minutes, we have code & user documentation and unit tests.

Without ChatGPT's help, it takes a lot more time!

Benefits of Using ChatGPT for Code Documentation and Testing

To be a bit shorter, let's conclude these benefits that improve our code quality, save us time, and make our work more accessible to others:

  1. ChatGPT helps automate the process of writing code documentation, resulting in clear and concise documentation that's easy to read and understand. This saves developers valuable time and effort.
  2. ChatGPT can assist with unit testing, ensuring our code is thoroughly tested, free of errors, and meets industry standards. This helps to improve code quality.
  3. ChatGPT generates user-friendly documentation, making it easy for other contributors to understand and use our code. This ensures consistency in the documentation and increases accessibility for all users.

All these benefits promote teamwork and ensure that the code documentation is consistent and accurate.

Conclusion: Embracing AI-Assisted Documentation and Testing for Better Results

Overall, by using ChatGPT, we can focus only on writing great code without sacrificing documentation and testing.

Moreover, with the power of ChatGPT plugins, it can do much more!

ChatGPT seems to be a powerful tool for developers of all levels and backgrounds.

Whether you're a front-end developer or a full-stack developer, it can help you write high-quality code that meets industry standards and is accessible to all.

I'm trying to dive more into it and continue to give you hints, Subscribe to follow up!