Create Logos

Using AI to Test Your TypeScript Code with Jest

Using AI to Test Your TypeScript Code with Jest blog article main image

A GPT-Assisted Approach

Introduction

The utilization of AI like GPT to generate unit tests for existing code can offer several key benefits:

  1. Boosting Productivity
    Writing unit tests can be time-consuming. AI can help automate this process, thereby freeing developers to focus on more complex tasks, thereby improving productivity.
  2. Increasing Test Coverage
    AI can potentially generate a more comprehensive set of tests, covering edge cases that human developers might overlook. This can lead to improved test coverage and higher code quality.
  3. Improving Code Quality
    With AI-generated unit tests, issues and bugs can be discovered and fixed sooner, leading to improved code quality and reliability.
  4. Consistency
    AI can ensure a consistent level of quality and thoroughness in unit tests, something that can vary between different developers.
  5. Learning Tool
    For novice developers, AI-generated unit tests can serve as examples of how to write effective tests, providing a valuable learning tool.
  6. Reducing Costs
    By identifying bugs and issues early in the development process, AI-generated unit tests can help reduce the cost of debugging and maintenance later in the software lifecycle.
  7. Supporting Refactoring Efforts
    Unit tests are crucial for safe refactoring of code. AI can help generate the necessary tests that ensure that functionality remains consistent throughout the refactoring process.
  8. 24/7 Operation
    AI doesn't require breaks, and can generate tests around the clock, thereby providing constant support to the development team.

It's important to note, however, that while AI can help with unit test generation, it doesn't completely replace the need for human testers. Developers and testers still need to review AI-generated tests to ensure they make sense and cover the necessary functionality. AI is a tool that can enhance and support the testing process, but it doesn't eliminate the need for human insight and expertise.

In this post, we'll use JestJS, a popular JavaScript testing framework, to write unit tests for our TypeScript user authentication library.

GPT Prompt

Generate unit tests for the following code. Use the JestJS unit testing framework https://jestjs.io/). Generate at least 4 test cases for each method.

import * as bcrypt from 'bcrypt';

class UserAuth {
  static validateEmail(email: string): boolean {
    let emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
  }
  
  static validatePassword(password: string): boolean {
    let passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/;
    return passwordRegex.test(password);
  }

  static splitEmail(email: string): [string, string, string] {
    const [username, domain] = email.split('@');
    const domainParts = domain.split('.');
    const topLevelDomain = domainParts[domainParts.length - 1];

    return [username, domain, topLevelDomain];
  }
  
  static async hashPassword(password: string): Promise<string> {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    return hashedPassword;
  }
  
  static async validateHash(password: string, hash: string): Promise<boolean> {
    return await bcrypt.compare(password, hash);
  }
}

Prompt Overview

In this case, the AI was asked to create unit tests for a user authentication library using the JestJS testing framework. The AI crafted tests for each method in the library, ensuring each function works as expected when given both correct and incorrect inputs.

GPT Response

Here's how we could structure our tests using Jest:

import * as bcrypt from 'bcrypt';
import { UserAuth } from './UserAuth';  // Assume UserAuth is in UserAuth.ts

describe('UserAuth', () => {
  test('validates correct email', () => {
    expect(UserAuth.validateEmail('[email protected]')).toBe(true);
  });

  test('rejects incorrect email', () => {
    expect(UserAuth.validateEmail('not an email')).toBe(false);
  });

  test('validates correct password', () => {
    expect(UserAuth.validatePassword('Password123!')).toBe(true);
  });

  test('rejects incorrect password', () => {
    expect(UserAuth.validatePassword('password')).toBe(false);
  });

  test('splits email correctly', () => {
    expect(UserAuth.splitEmail('[email protected]')).toEqual(['test', 'example.com', 'com']);
  });

  test('hashes and validates password correctly', async () => {
    const password = 'Password123!';
    const hash = await UserAuth.hashPassword(password);
    expect(await UserAuth.validateHash(password, hash)).toBe(true);
  });
});

GPT Response Overview

  1. We start with validateEmail and validatePassword methods, testing them with both correct and incorrect input values.
  2. We then test the splitEmail method, checking if it correctly splits the email into username, domain name, and top-level domain.
  3. In the above code, we use Jest's describe and test functions to group our tests and define our test cases.
  4. Finally, we test hashPassword and validateHash together, creating a password hash and then verifying it. These tests are asynchronous, so we use the async keyword and await expression.

Benefits and Conclusion

Writing unit tests for your code brings several benefits. It helps catch bugs early, provides documentation, simplifies code integration, and ensures code quality.

By testing individual units of code like functions or methods, you can ensure each piece works correctly on its own before integrating it with others.

Using JestJS with TypeScript can make your testing process easier and more effective, providing clear and comprehensive testing for your JavaScript and TypeScript projects.

Was This Helpful?

If you found this blog post helpful, feel free to check out our other blog posts on using AI in software development at the Logobean Blog!

Blog CTA

Get Started For Free. No Signup Required.

1. Get started

Add your business name to instantly generate an endless selection of logos and brands.

Icon AI business name & slogan generator
Icon Select a business or general logo theme
Icon Select a logo name layout (for 2+ word names)
Icon Generate unlimited logos in seconds
Icon No sign up required
Start Logobean Logo Maker
Logobean logo maker get started
Logobean logo maker select styles live preview favorite

2. Select styles, live preview and favorite your logos

Select your logo styles to refine the generated logos, click any logo to view it in the live previews & logo style guide and favorite the logos that you love.

Icon Select styles to refine your generated logos
Icon Filter logo layouts, icons, colors, fonts & more
Icon Revolutionary & interactive logo previews
Icon Live & interactive logo style guide
Icon Save logos that you love to your favorites
Start Logobean Logo Maker

3. Edit and perfect your logo

Edit any logo to perfection using our intuitive logo and rich text editors.

Icon Intuitive logo editors for every logo layout
Icon Rich text editors for your name and slogan
Icon Icon, color and font selectors
Icon Smart icon coloring
Icon Live preview your logo whilst editing
Start Logobean Logo Maker
Logobean logo maker edit logo editor
Logobean logo maker select styles live preview favorite

4. Download your logo files & more

Once you've found the perfect logo, download and use your logo package instantly!

Icon High quality PNG & SVG logo files
Icon 100+ on-brand designs
Icon Ready-to-upload social media profile & cover images
Icon Brand color palette
Icon Manage your logos, brand and downloads on-going
Start Logobean Logo Maker

Ready to get started?