Claude
Skills
Sign in
Back

Code Quality

Included with Lifetime
$97 forever

Expertise in automated testing, code review practices, and quality standards enforcement. Activates when working with "lint", "test", "review", "coverage", "quality", "standards", or test automation.

Code Review

What this skill does


# Code Quality Skill

## Overview

Establish and maintain high code quality standards through comprehensive testing strategies, automated quality gates, and systematic code review practices. This skill encompasses unit testing, integration testing, end-to-end testing with Playwright and Selenium, linting, code coverage analysis, and quality metrics enforcement.

## Core Competencies

### Testing Strategy

**Design Test Pyramid:**

Implement a balanced testing strategy with proper distribution:

- **70% Unit Tests** - Fast, isolated, testing individual functions and components
- **20% Integration Tests** - Testing component interactions and API contracts
- **10% End-to-End Tests** - Testing critical user journeys and workflows

**Unit Testing Best Practices:**

Write focused, maintainable unit tests using the AAA pattern (Arrange, Act, Assert):

```typescript
// user.service.spec.ts
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { UserService } from './user.service';
import { UserRepository } from './user.repository';

describe('UserService', () => {
  let userService: UserService;
  let userRepository: UserRepository;

  beforeEach(() => {
    userRepository = {
      findById: vi.fn(),
      save: vi.fn(),
      delete: vi.fn(),
    } as unknown as UserRepository;

    userService = new UserService(userRepository);
  });

  describe('getUserById', () => {
    it('should return user when user exists', async () => {
      // Arrange
      const mockUser = { id: '1', name: 'John Doe', email: '[email protected]' };
      vi.mocked(userRepository.findById).mockResolvedValue(mockUser);

      // Act
      const result = await userService.getUserById('1');

      // Assert
      expect(result).toEqual(mockUser);
      expect(userRepository.findById).toHaveBeenCalledWith('1');
      expect(userRepository.findById).toHaveBeenCalledTimes(1);
    });

    it('should throw error when user does not exist', async () => {
      // Arrange
      vi.mocked(userRepository.findById).mockResolvedValue(null);

      // Act & Assert
      await expect(userService.getUserById('1')).rejects.toThrow('User not found');
    });
  });

  describe('createUser', () => {
    it('should create user with valid data', async () => {
      // Arrange
      const userData = { name: 'Jane Doe', email: '[email protected]' };
      const savedUser = { id: '2', ...userData };
      vi.mocked(userRepository.save).mockResolvedValue(savedUser);

      // Act
      const result = await userService.createUser(userData);

      // Assert
      expect(result).toEqual(savedUser);
      expect(userRepository.save).toHaveBeenCalledWith(expect.objectContaining(userData));
    });

    it('should validate email format', async () => {
      // Arrange
      const invalidData = { name: 'Jane Doe', email: 'invalid-email' };

      // Act & Assert
      await expect(userService.createUser(invalidData)).rejects.toThrow('Invalid email format');
    });
  });
});
```

**Integration Testing Patterns:**

Test component interactions and external service integration:

```typescript
// api.integration.spec.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import request from 'supertest';
import { createApp } from '../app';
import { DatabaseConnection } from '../database';

describe('User API Integration Tests', () => {
  let app: Express.Application;
  let db: DatabaseConnection;

  beforeAll(async () => {
    // Setup test database
    db = await DatabaseConnection.connect({
      host: 'localhost',
      database: 'test_db',
    });

    await db.migrate();
    app = createApp(db);
  });

  afterAll(async () => {
    await db.cleanup();
    await db.disconnect();
  });

  describe('POST /api/users', () => {
    it('should create new user with valid data', async () => {
      const userData = {
        name: 'John Doe',
        email: '[email protected]',
        password: 'SecurePass123!',
      };

      const response = await request(app)
        .post('/api/users')
        .send(userData)
        .expect(201);

      expect(response.body).toMatchObject({
        id: expect.any(String),
        name: userData.name,
        email: userData.email,
      });
      expect(response.body.password).toBeUndefined();
    });

    it('should return 400 for duplicate email', async () => {
      const userData = {
        name: 'Jane Doe',
        email: '[email protected]', // Duplicate from previous test
        password: 'SecurePass123!',
      };

      const response = await request(app)
        .post('/api/users')
        .send(userData)
        .expect(400);

      expect(response.body.error).toBe('Email already exists');
    });
  });

  describe('GET /api/users/:id', () => {
    it('should return user by id', async () => {
      // Create user first
      const createResponse = await request(app)
        .post('/api/users')
        .send({ name: 'Test User', email: '[email protected]', password: 'Pass123!' });

      const userId = createResponse.body.id;

      // Fetch user
      const response = await request(app)
        .get(`/api/users/${userId}`)
        .expect(200);

      expect(response.body).toMatchObject({
        id: userId,
        name: 'Test User',
        email: '[email protected]',
      });
    });

    it('should return 404 for non-existent user', async () => {
      const response = await request(app)
        .get('/api/users/non-existent-id')
        .expect(404);

      expect(response.body.error).toBe('User not found');
    });
  });
});
```

### End-to-End Testing

**Playwright Testing Framework:**

Implement comprehensive E2E tests with Playwright for modern web applications:

```typescript
// tests/e2e/user-journey.spec.ts
import { test, expect, Page } from '@playwright/test';

test.describe('User Registration and Login Flow', () => {
  let page: Page;

  test.beforeEach(async ({ page: testPage }) => {
    page = testPage;
    await page.goto('https://app.example.com');
  });

  test('complete user registration journey', async () => {
    // Navigate to registration
    await page.click('text=Sign Up');
    await expect(page).toHaveURL(/.*\/register/);

    // Fill registration form
    await page.fill('input[name="name"]', 'Test User');
    await page.fill('input[name="email"]', `test-${Date.now()}@example.com`);
    await page.fill('input[name="password"]', 'SecurePassword123!');
    await page.fill('input[name="confirmPassword"]', 'SecurePassword123!');

    // Submit form
    await page.click('button[type="submit"]');

    // Verify success
    await expect(page).toHaveURL(/.*\/dashboard/);
    await expect(page.locator('text=Welcome, Test User')).toBeVisible();
  });

  test('login with valid credentials', async () => {
    // Navigate to login
    await page.click('text=Log In');

    // Fill login form
    await page.fill('input[name="email"]', '[email protected]');
    await page.fill('input[name="password"]', 'KnownPassword123!');

    // Submit
    await page.click('button[type="submit"]');

    // Verify dashboard access
    await expect(page).toHaveURL(/.*\/dashboard/);
    await expect(page.locator('[data-testid="user-menu"]')).toBeVisible();
  });

  test('display validation errors for invalid input', async () => {
    await page.click('text=Sign Up');

    // Fill invalid email
    await page.fill('input[name="email"]', 'invalid-email');
    await page.fill('input[name="password"]', 'weak');

    // Try to submit
    await page.click('button[type="submit"]');

    // Verify error messages
    await expect(page.locator('text=Invalid email format')).toBeVisible();
    await expect(page.locator('text=Password must be at least 8 characters')).toBeVisible();
  });

  test('handle network errors gracefully', async () => {
    // Simulate offline mode
    await page.context().setOffline(true);

    await page.click('text=Log In');
    await page.fill('input[name="email"]', '[email protected]');
    await page.fill('input[name="passwor

Related in Code Review