Command Palette

Search for a command to run...

Назад к скиллам
скилл № 87153

testing-strategy

Comprehensive testing skill covering unit, integration, and e2e testing with TDD. Use when writing tests, improving coverage, or setting up testing…

БесплатноБез исполняемых скриптов
VoDaiLoczот VoDaiLocz★ 28 звёзд на GitHub

Установить testing-strategy в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

🧪 Testing Strategy Skill

Philosophy: If it's not tested, it's broken. You just don't know it yet.

When to Use

Use this skill when:

  • Writing new code (TDD approach)
  • Adding tests to existing code
  • Improving test coverage
  • Fixing flaky tests
  • Setting up testing infrastructure
  • Debugging test failures

Do NOT use this skill when:

  • Just running existing tests
  • Quick syntax check

The Testing Pyramid

                 ╱╲
                ╱  ╲
               ╱ E2E╲           Few, slow, expensive
              ╱──────╲          Full system tests
             ╱        ╲
            ╱Integration╲       Medium amount
           ╱────────────╲       Component interaction
          ╱              ╲
         ╱   Unit Tests   ╲     Many, fast, cheap
        ╱──────────────────╲    Single unit isolation

TDD Workflow: RED → GREEN → REFACTOR

Step 1: RED (Write Failing Test)

// Write the test BEFORE the implementation
describe('calculateDiscount', () => {
  it('should apply 10% discount for orders over $100', () => {
    // This test will FAIL because function doesn't exist yet
    const result = calculateDiscount(150);
    expect(result).toBe(135);
  });
});

Run test → Should FAIL (RED)

Step 2: GREEN (Minimal Implementation)

// Write the MINIMUM code to pass the test
function calculateDiscount(amount: number): number {
  if (amount > 100) {
    return amount * 0.9;
  }
  return amount;
}

Run test → Should PASS (GREEN)

Step 3: REFACTOR (Improve)

// Improve code while keeping tests green
const DISCOUNT_THRESHOLD = 100;
const DISCOUNT_RATE = 0.1;

function calculateDiscount(amount: number): number {
  if (amount > DISCOUNT_THRESHOLD) {
    return amount * (1 - DISCOUNT_RATE);
  }
  return amount;
}

Run test → Should still PASS


Unit Testing Patterns

Basic Structure (AAA Pattern)

describe('UserService', () => {
  describe('createUser', () => {
    it('should create user with valid data', async () => {
      // Arrange
      const userData = { email: '[email protected]', name: 'Test' };
      const mockRepo = { create: jest.fn().mockResolvedValue({ id: '1', ...userData }) };
      const service = new UserService(mockRepo);
      
      // Act
      const result = await service.createUser(userData);
      
      // Assert
      expect(result.id).toBe('1');
      expect(result.email).toBe(userData.email);
      expect(mockRepo.create).toHaveBeenCalledWith(userData);
    });
  });
});

Testing Error Cases

describe('createUser', () => {
  it('should throw on duplicate email', async () => {
    // Arrange
    const mockRepo = {
      findByEmail: jest.fn().mockResolvedValue({ id: 'existing' }),
    };
    const service = new UserService(mockRepo);
    
    // Act & Assert
    await expect(
      service.createUser({ email: '[email protected]' })
    ).rejects.toThrow('Email already registered');
  });
});

Testing Async Code

describe('fetchUserData', () => {
  it('should fetch and transform user data', async () => {
    // Arrange
    const mockApi = {
      get: jest.fn().mockResolvedValue({ data: { name: 'John' } }),
    };
    
    // Act
    const result = await fetchUserData(mockApi, 'user-id');
    
    // Assert
    expect(result).toEqual({ name: 'John' });
    expect(mockApi.get).toHaveBeenCalledWith('/users/user-id');
  });
  
  it('should handle API errors gracefully', async () => {
    const mockApi = {
      get: jest.fn().mockRejectedValue(new Error('Network error')),
    };
    
    await expect(fetchUserData(mockApi, 'user-id'))
      .rejects.toThrow('Failed to fetch user');
  });
});

Mocking Strategies

Mock Functions

// Create mock function
const mockFn = jest.fn();

// Define return value
mockFn.mockReturnValue('static value');
mockFn.mockResolvedValue('async value');
mockFn.mockRejectedValue(new Error('error'));

// Implementation
mockFn.mockImplementation((x) => x * 2);

// Verify calls
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2');
expect(mockFn).toHaveBeenCalledTimes(3);

Mock Modules

// Mock entire module
jest.mock('./database', () => ({
  connect: jest.fn(),
  query: jest.fn(),
}));

// Mock with factory
jest.mock('./config', () => ({
  get: (key: string) => {
    const config = { API_URL: 'http://test-api.com' };
    return config[key];
  },
}));

Spying

// Spy on existing method
const spy = jest.spyOn(userService, 'sendEmail');

// Call the code
await userService.createUser({ email: '[email protected]' });

// Verify the spy
expect(spy).toHaveBeenCalled();

// Restore original
spy.mockRestore();

Integration Testing

API Integration Tests

describe('POST /users', () => {
  let app: Express;
  let db: Database;
  
  beforeAll(async () => {
    db = await
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл testing-strategy?

Comprehensive testing skill covering unit, integration, and e2e testing with TDD. Use when writing tests, improving coverage, or setting up testing infrastructure. Keywords: test, TDD, unit test, integration, e2e, coverage, mock, jest, vitest

Как установить скилл testing-strategy?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл testing-strategy запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить testing-strategy с