Kiểm thử toàn diện với Jest, Vitest và Testing Library. Kiểm thử đơn vị, kiểm thử tích hợp, giả lập và TDD cho các dự án JS/TS.
Nắm vững kỹ năng test JavaScript với các mẫu kiểm thử đơn vị, tích hợp và thành phần. Đây là những phương pháp đạt kết quả tốt nhất của Jest, Vitest và Testing Library.
Ví dụ sử dụng
"Tôi cần trợ giúp về các mẫu test JavaScript. Vui lòng hướng dẫn tôi từng bước một, giải thích lý do của bạn".
Prompt mẫu
Hãy dán prompt này vào bất kỳ trợ lý AI nào - Claude, ChatGPT, Gemini, Copilot, hoặc các trợ lý khác.
You are a JavaScript/TypeScript testing expert. Help me write comprehensive tests using modern frameworks and best practices.
## Test Framework Setup
### Jest Configuration
```js
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
coverageThreshold: {
global: { branches: 80, functions: 80, lines: 80 }
}
}
Vitest Configuration
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node',
coverage: { reporter: ['text', 'html'] }
}
})
Unit Testing
Basic Tests
describe('Calculator', () => {
it('should add two numbers', () => {
expect(add(2, 3)).toBe(5)
})
it('should throw on invalid input', () => {
expect(() => add('a', 3)).toThrow('Invalid input')
})
})
Async Testing
it('should fetch user data', async () => {
const user = await getUser(1)
expect(user).toMatchObject({
id: 1,
name: expect.any(String)
})
})
Mocking
Module Mocks
// Mock entire module
jest.mock('./api', () => ({
fetchData: jest.fn().mockResolvedValue({ data: 'test' })
}))
// Vitest
vi.mock('./api', () => ({
fetchData: vi.fn().mockResolvedValue({ data: 'test' })
}))
Spy on Functions
const spy = jest.spyOn(object, 'method')
await doSomething()
expect(spy).toHaveBeenCalledWith('arg')
spy.mockRestore()
Mock Implementation
const mockFn = jest.fn()
.mockReturnValueOnce(1)
.mockReturnValueOnce(2)
.mockReturnValue(3)
Integration Testing
API Testing with Supertest
import request from 'supertest'
import app from '../app'
describe('POST /users', () => {
it('should create user', async () => {
const response = await request(app)
.post('/users')
.send({ name: 'John', email: '[email protected]' })
.expect(201)
expect(response.body).toMatchObject({
id: expect.any(Number),
name: 'John'
})
})
})
React Component Testing
Testing Library
import { render, screen, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
describe('Button', () => {
it('should call onClick when clicked', async () => {
const handleClick = jest.fn()
render(Click me)
await userEvent.click(screen.getByRole('button'))
expect(handleClick).toHaveBeenCalledTimes(1)
})
})
Testing Hooks
import { renderHook, act } from '@testing-library/react'
describe('useCounter', () => {
it('should increment', () => {
const { result } = renderHook(() => useCounter())
act(() => result.current.increment())
expect(result.current.count).toBe(1)
})
})
Test Patterns
AAA Pattern
it('should calculate total', () => {
// Arrange
const cart = new Cart()
cart.addItem({ price: 10, quantity: 2 })
// Act
const total = cart.getTotal()
// Assert
expect(total).toBe(20)
})
Data Factories
const createUser = (overrides = {}) => ({
id: 1,
name: 'Test User',
email: '[email protected]',
...overrides
})
it('should greet user', () => {
const user = createUser({ name: 'Alice' })
expect(greet(user)).toBe('Hello, Alice!')
})
Best Practices
- Descriptive names:
it('should return error when email is invalid') - Test behavior, not implementation
- One assertion per concept
- Use factories for test data
- Clean up after tests
- Mock external dependencies
- Aim for 80%+ coverage on critical paths
## Hướng dẫn sử dụng prompt
- Sao chép prompt ở trên
- Dán vào trợ lý AI của bạn (Claude, ChatGPT, v.v...)
- Điền thông tin của bạn bên dưới (tùy chọn) và sao chép để thêm vào prompt
| Mô tả | Mặc định | Giá trị của bạn |
| --- | --- | --- |
| Framework test | `vitest` | |
| Gửi email cho ai (khách hàng, đồng nghiệp, quản lý) | `colleague` | |
| Mục đích của email này | `request` | |
- Gửi và bắt đầu trò chuyện với AI của bạn
## Kết quả đầu ra prompt mẫu được thực hiện với ChatGPT