Prompt test JavaScript

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
```ts
// vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    coverage: { reporter: ['text', 'html'] }
  }
})
```

## Unit Testing

### Basic Tests
```ts
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
```ts
it('should fetch user data', async () => {
  const user = await getUser(1)
  expect(user).toMatchObject({
    id: 1,
    name: expect.any(String)
  })
})
```

## Mocking

### Module Mocks
```ts
// 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
```ts
const spy = jest.spyOn(object, 'method')
await doSomething()
expect(spy).toHaveBeenCalledWith('arg')
spy.mockRestore()
```

### Mock Implementation
```ts
const mockFn = jest.fn()
  .mockReturnValueOnce(1)
  .mockReturnValueOnce(2)
  .mockReturnValue(3)
```

## Integration Testing

### API Testing with Supertest
```ts
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: 'john@test.com' })
      .expect(201)

    expect(response.body).toMatchObject({
      id: expect.any(Number),
      name: 'John'
    })
  })
})
```

## React Component Testing

### Testing Library
```tsx
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
```tsx
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
```ts
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
```ts
const createUser = (overrides = {}) => ({
  id: 1,
  name: 'Test User',
  email: 'test@example.com',
  ...overrides
})

it('should greet user', () => {
  const user = createUser({ name: 'Alice' })
  expect(greet(user)).toBe('Hello, Alice!')
})
```

## Best Practices

1. **Descriptive names**: `it('should return error when email is invalid')`
2. **Test behavior, not implementation**
3. **One assertion per concept**
4. **Use factories for test data**
5. **Clean up after tests**
6. **Mock external dependencies**
7. **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 địnhGiá trị của bạn
Framework testvitest
Gửi email cho ai (khách hàng, đồng nghiệp, quản lý)colleague
Mục đích của email nàyrequest
  • 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

Thứ Năm, 07/05/2026 09:01
31 👨 16

Prompt liên quan

Xác thực tài khoản!

Theo Nghị định 147/2024/ND-CP, bạn cần xác thực tài khoản trước khi sử dụng tính năng này. Chúng tôi sẽ gửi mã xác thực qua SMS hoặc Zalo tới số điện thoại mà bạn nhập dưới đây:

Số điện thoại chưa đúng định dạng!
Số điện thoại này đã được xác thực!
Bạn có thể dùng Sđt này đăng nhập tại đây!
Lỗi gửi SMS, liên hệ Admin
0 Bình luận
Sắp xếp theo