Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

JavaScript Testing Patterns

БесплатноБез исполняемых скриптовНе проверен

Modern JavaScript testing strategies with Jest, Mocha, and testing best practices covering unit testing, integration testing, mocking, async patterns, and DOM…

PramodDuttaот PramodDutta★ 253 звезды на GitHub

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

JavaScript Testing Patterns Skill

You are an expert JavaScript developer specializing in testing patterns and methodologies. When the user asks you to write, review, or improve JavaScript tests, follow these detailed instructions.

Core Principles

  1. Test behavior, not implementation -- Tests should verify what code does, not how it works internally.
  2. Fast feedback loops -- Unit tests should run in milliseconds.
  3. Arrange-Act-Assert -- Clear three-phase structure for every test.
  4. Deterministic tests -- Same input always produces same output.
  5. Isolated tests -- No shared state or dependencies between tests.

Project Structure

project/
  src/
    services/
      user.service.js
      user.service.test.js
    utils/
      validators.js
      validators.test.js
    components/
      Button.jsx
      Button.test.jsx
  __tests__/
    integration/
      api.test.js
    e2e/
      checkout.test.js
  __mocks__/
    axios.js
    localStorage.js
  jest.config.js

Jest Configuration

// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  roots: ['<rootDir>/src'],
  testMatch: ['**/__tests__/**/*.js', '**/?(*.)+(spec|test).js'],
  collectCoverageFrom: [
    'src/**/*.{js,jsx}',
    '!src/**/*.test.{js,jsx}',
    '!src/**/index.js',
  ],
  coverageThresholds: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
  },
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
  },
  clearMocks: true,
  restoreMocks: true,
};

Basic Testing Patterns

1. Testing Pure Functions

// validators.js
export function isValidEmail(email) {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

export function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}

export function formatCurrency(amount, currency = 'USD') {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency,
  }).format(amount);
}
// validators.test.js
import { isValidEmail, calculateTotal, formatCurrency } from './validators';

describe('Validators', () => {
  describe('isValidEmail', () => {
    it('should return true for valid emails', () => {
      expect(isValidEmail('[email protected]')).toBe(true);
      expect(isValidEmail('[email protected]')).toBe(true);
      expect(isValidEmail('[email protected]')).toBe(true);
    });

    it('should return false for invalid emails', () => {
      expect(isValidEmail('')).toBe(false);
      expect(isValidEmail('not-an-email')).toBe(false);
      expect(isValidEmail('@missing-local.com')).toBe(false);
      expect(isValidEmail('missing@domain')).toBe(false);
    });
  });

  describe('calculateTotal', () => {
    it('should calculate total for single item', () => {
      const items = [{ price: 10, quantity: 2 }];
      expect(calculateTotal(items)).toBe(20);
    });

    it('should calculate total for multiple items', () => {
      const items = [
        { price: 10, quantity: 2 },
        { price: 5, quantity: 3 },
      ];
      expect(calculateTotal(items)).toBe(35);
    });

    it('should return 0 for empty array', () => {
      expect(calculateTotal([])).toBe(0);
    });
  });

  describe('formatCurrency', () => {
    it('should format USD by default', () => {
      expect(formatCurrency(1234.56)).toBe('$1,234.56');
    });

    it('should format different currencies', () => {
      expect(formatCurrency(1234.56, 'EUR')).toContain('1,234.56');
      expect(formatCurrency(1234.56, 'GBP')).toContain('1,234.56');
    });
  });
});

2. Testing Classes and Services

// user.service.js
export class UserService {
  constructor(apiClient, cache) {
    this.apiClient = apiClient;
    this.cache = cache;
  }

  async getUser(id) {
    const cached = this.cache.get(`user:${id}`);
    if (cached) return JSON.parse(cached);

    const user = await this.apiClient.get(`/users/${id}`);
    this.cache.set(`user:${id}`, JSON.stringify(user));
    return user;
  }

  async createUser(userData) {
    const user = await this.apiClient.post('/users', userData);
    return user;
  }

  async deleteUser(id) {
    const user = await this.getUser(id);
    if (!user) throw new Error('User not found');
    await this.apiClient.delete(`/users/${id}`);
    this.cache.delete(`user:${id}`);
  }
}
// user.service.test.js
import { UserService } from './user.service';

describe('UserService', () => {
  let userService;
  let mockApiClient;
  let mockCache;

  beforeEach(() => {
    mockApiClient = {
      get: jest.fn(),
      post: jest.fn(),
      delete: jest.fn(),
    };
    mockCache = {
      get: jest.fn(),
      set: jest.fn(),
      delete: jest.fn(),
    };
    userService = new
Полный SKILL.md на GitHub

Установить JavaScript Testing Patterns в Claude Code и Claude Desktop

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

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

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

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

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

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

FAQ

Что делает скилл JavaScript Testing Patterns?

Modern JavaScript testing strategies with Jest, Mocha, and testing best practices covering unit testing, integration testing, mocking, async patterns, and DOM testing.

Как установить скилл JavaScript Testing Patterns?

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

Скилл JavaScript Testing Patterns запускает скрипты?

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

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

Сравнить JavaScript Testing Patterns с