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★ 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
- Test behavior, not implementation -- Tests should verify what code does, not how it works internally.
- Fast feedback loops -- Unit tests should run in milliseconds.
- Arrange-Act-Assert -- Clear three-phase structure for every test.
- Deterministic tests -- Same input always produces same output.
- 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
Установить 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), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic