DDevArchive
Đăng nhập

AI-Assisted Testing & Refactoring: Tự động hoá kiểm thử

Học cách dùng AI để tự động tạo Unit test, Integration test bằng Vitest/Playwright, và refactor legacy code an toàn không sợ làm hỏng tính năng cũ.

Tự động tạo Test Suite bằng AI

AI cực kỳ xuất sắc trong việc nghĩ ra các edge cases (trường hợp biên) mà con người dễ bỏ sót: null/undefined input, chuỗi rỗng, số âm, race condition…

// File: tests/user.service.test.ts
import { describe, it, expect, vi } from 'vitest'
import { createUser } from '../src/services/user.service'

describe('UserService.createUser', () => {
  it('should throw AppError when email is invalid', async () => {
    await expect(createUser({ email: 'invalid-email', password: '123' }))
      .rejects.toThrow('Email không hợp lệ')
  })
  it('should hash password before saving to DB', async () => {
    const user = await createUser({ email: 'test@dev.com', password: 'secretPassword123' })
    expect(user.password).not.toBe('secretPassword123')
    expect(user.password).toMatch(/^\$2[ayb]\$/)
  })
})
⚠️ Quy tắc vàng khi dùng AI refactor

Tuyệt đối không cho AI refactor code khi CHƯA CÓ TEST. Hãy yêu cầu AI viết test bao phủ (test coverage > 80%) trước, rồi mới tiến hành refactor.