Комментарии (2)
🐱
claude-haiku-4.5PrepBro AI30 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Unit Testing — тестирование отдельных компонентов
Unit Testing (модульное тестирование) — это процесс тестирования отдельных, изолированных единиц кода (функции, методы, классы).
Концепция
function add(a, b) {
return a + b;
}
test('add(2, 3) should return 5', () => {
const result = add(2, 3);
expect(result).toBe(5);
});
Пример с Jest
function calculateDiscount(price, discountPercent) {
if (discountPercent < 0 || discountPercent > 100) {
throw new Error('Invalid discount');
}
return price * (1 - discountPercent / 100);
}
describe('calculateDiscount', () => {
test('should calculate discount correctly', () => {
expect(calculateDiscount(100, 20)).toBe(80);
});
test('should throw error for invalid discount', () => {
expect(() => calculateDiscount(100, -10)).toThrow('Invalid discount');
});
test('should return full price for 0% discount', () => {
expect(calculateDiscount(100, 0)).toBe(100);
});
});
Мокирование зависимостей
class UserRepository {
constructor(database) {
this.database = database;
}
getUserById(id) {
return this.database.query(`SELECT * FROM users WHERE id = ${id}`);
}
}
test('should get user from repository', () => {
const mockDb = {
query: jest.fn().mockReturnValue({ id: 1, name: 'John' })
};
const repo = new UserRepository(mockDb);
const user = repo.getUserById(1);
expect(user).toEqual({ id: 1, name: 'John' });
expect(mockDb.query).toHaveBeenCalledWith('SELECT * FROM users WHERE id = 1');
});
AAA Pattern (Arrange, Act, Assert)
test('should validate email', () => {
// Arrange — подготовка
const email = 'test@example.com';
// Act — выполнение
const isValid = validateEmail(email);
// Assert — проверка
expect(isValid).toBe(true);
});
Unit vs Integration Testing
| Аспект | Unit | Integration |
|---|---|---|
| Что | Отдельная функция | Несколько компонентов |
| Скорость | Быстро (мс) | Медленнее (сек) |
| Мокирование | Да | Нет |
| Уровень | Функции | Системы |
Best Practices
// 1. Одно утверждение per test
test('should create user with valid data', () => {
expect(createUser('John')).toBe('John');
});
// 2. Descriptive names
test('should create user with valid data', () => {...});
// 3. Test edge cases
test('with 0% discount', () => expect(calculateDiscount(100, 0)).toBe(100));
test('with 100% discount', () => expect(calculateDiscount(100, 100)).toBe(0));
test('negative throws', () => expect(() => calculateDiscount(100, -10)).toThrow());
// 4. Независимые тесты (no interdependencies)
Key takeaway
- Unit Testing = тестирование отдельных функций
- Изолировано от остальной системы (mocks)
- Быстро выполняется
- Обязательный элемент TDD
- Целевое покрытие: 80-90%