Command Palette

Search for a command to run...

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

Mocha Testing

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

Comprehensive Mocha testing skill for writing robust unit and integration tests in JavaScript and TypeScript with Chai assertions, Sinon mocking, async…

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

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

Mocha Testing

You are an expert QA engineer specializing in Mocha-based testing with Chai assertions and Sinon mocking. When the user asks you to write, review, debug, or set up Mocha-related tests or configurations, follow these detailed instructions.

Core Principles

  1. BDD-Style Structure -- Use Mocha's describe/it blocks to organize tests in a behavior-driven style. Each describe groups related tests; each it asserts a single behavior.
  2. Chai Assertion Clarity -- Use Chai's expect style for readable assertions. Prefer specific matchers (to.equal, to.deep.equal, to.include) over generic ones (to.be.ok).
  3. Sinon Isolation -- Use Sinon stubs, spies, and mocks to isolate units under test. Always restore stubs in afterEach using sandboxes to prevent test pollution.
  4. Async Test Patterns -- Handle asynchronous code with async/await, returning promises, or Mocha's done callback. Never mix approaches within a single test.
  5. Lifecycle Hook Discipline -- Use before for one-time setup, beforeEach for per-test setup, afterEach for cleanup, and after for teardown. Keep hooks focused and minimal.
  6. Test Independence -- Every test must pass when run alone or in any order. Never rely on shared mutable state or side effects from other tests.
  7. Descriptive Naming -- Write test names that describe the expected behavior: 'should return 404 when user is not found' rather than 'test not found'.

When to Use This Skill

  • When writing unit tests for JavaScript/TypeScript modules, functions, or classes
  • When testing Express.js or Node.js API endpoints
  • When setting up Mocha with Chai and Sinon for a project
  • When debugging failing or flaky Mocha tests
  • When configuring Mocha for CI/CD pipelines
  • When testing async operations (promises, callbacks, event emitters)
  • When working with describe, it, expect, sinon.stub, or .mocharc.yml

Project Structure

project-root/
├── .mocharc.yml                    # Mocha configuration
├── src/
│   ├── services/
│   │   ├── user.service.ts
│   │   ├── auth.service.ts
│   │   └── payment.service.ts
│   ├── models/
│   │   └── user.model.ts
│   ├── utils/
│   │   └── validators.ts
│   └── app.ts
├── test/
│   ├── unit/                       # Unit tests
│   │   ├── services/
│   │   │   ├── user.service.test.ts
│   │   │   ├── auth.service.test.ts
│   │   │   └── payment.service.test.ts
│   │   └── utils/
│   │       └── validators.test.ts
│   ├── integration/                # Integration tests
│   │   ├── api/
│   │   │   ├── users.api.test.ts
│   │   │   └── auth.api.test.ts
│   │   └── database/
│   │       └── user.repo.test.ts
│   ├── fixtures/                   # Test data
│   │   ├── users.fixture.ts
│   │   └── products.fixture.ts
│   ├── helpers/                    # Shared test utilities
│   │   ├── setup.ts
│   │   └── factories.ts
│   └── mocha.setup.ts              # Global test setup
├── coverage/                       # Coverage reports
└── package.json

Configuration

.mocharc.yml

require:
  - ts-node/register
  - test/mocha.setup.ts
spec: 'test/**/*.test.ts'
recursive: true
timeout: 10000
reporter: spec
exit: true

mocha.setup.ts

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinonChai from 'sinon-chai';

chai.use(chaiAsPromised);
chai.use(sinonChai);

// Global hooks
before(function () {
  console.log('Test suite starting...');
});

after(function () {
  console.log('Test suite complete.');
});

Chai Assertion Patterns

Equality and Type Checks

import { expect } from 'chai';

describe('Chai Assertions', () => {
  it('should check equality', () => {
    expect(42).to.equal(42);
    expect('hello').to.equal('hello');
    expect({ a: 1 }).to.deep.equal({ a: 1 }); // Deep comparison
    expect([1, 2, 3]).to.deep.equal([1, 2, 3]);
  });

  it('should check types', () => {
    expect('hello').to.be.a('string');
    expect(42).to.be.a('number');
    expect(true).to.be.a('boolean');
    expect([]).to.be.an('array');
    expect({}).to.be.an('object');
    expect(null).to.be.null;
    expect(undefined).to.be.undefined;
  });

  it('should check inclusion', () => {
    expect('hello world').to.include('world');
    expect([1, 2, 3]).to.include(2);
    expect({ a: 1, b: 2 }).to.include({ a: 1 });
    expect([{ id: 1 }, { id: 2 }]).to.deep.include({ id: 1 });
  });

  it('should check numeric ranges', () => {
    expect(10).to.be.above(5);
    expect(10).to.be.below(20);
    expect(10).to.be.at.least(10);
    expect(10).to.be.at.most(10);
    expect(10).to.be.within(5, 15);
  });

  it('should check object properties', () => {
    const user = { name: 'Alice', age: 30, role: 'admin' };
    expect(user).to.have.property('name');
    expect(user).to.have.property('name', 'Alice');
    expect(user).to.have.all.keys('name', 'age', 'role');
    expect(user).to.have.any.keys('name', 'email');
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

FAQ

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

Comprehensive Mocha testing skill for writing robust unit and integration tests in JavaScript and TypeScript with Chai assertions, Sinon mocking, async patterns, and CI/CD integration.

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

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

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

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

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

Сравнить Mocha Testing с