The utilization of AI like GPT to generate unit tests for existing code can offer several key benefits:
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.
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);
}
}
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.
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);
});
});
validateEmail
and validatePassword
methods, testing them with both correct
and incorrect input values.splitEmail
method, checking if it correctly splits the email into
username, domain name, and top-level domain.describe
and test
functions to group our tests and
define our test cases.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.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.
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!
Add your business name to instantly generate an endless selection of logos and brands.
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.
Edit any logo to perfection using our intuitive logo and rich text editors.
Once you've found the perfect logo, download and use your logo package instantly!