Command Palette

Search for a command to run...

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

js-unit-tests

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

Use for any question or task about JavaScript or TypeScript unit tests with Jest or Vitest, including quick how-to questions and tests for one function…

testlandот testland★ 18 звёзд на GitHub

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

js-unit-tests

Overview

The two mainstream JS/TS unit frameworks share one Jest-shaped API and split by build tool:

  • Jest (jestjs.io/docs/getting-started) - Meta-built, batteries-included: expect matchers, snapshot testing, mocking (jest.fn / jest.mock / jest.spyOn), and Istanbul coverage in one package. Home turf: React (CRA / older Next.js), React Native, Node services.
  • Vitest (vitest.dev/guide) - Vite-native: "Vitest reads your vite.config.* by default, so your existing Vite plugins and configuration work out-of-the-box." Jest-compatible API (expect, vi.fn, vi.mock), native ESM, in-source testing, browser mode.

This skill targets the per-framework lifecycle (configure / run / mock / coverage / CI), NOT test code hygiene - for assertion quality, AAA structure, and mocking anti-patterns see test-code-conventions (qa-test-review).

Choosing a framework

  1. Match the existing convention first. A repo with jest.config.* (or a "jest" package.json block) stays on Jest; one with vitest.config.* or a test block in vite.config.* stays on Vitest. Never mix two unit frameworks in one package.
  2. New code in a Vite project (Vue, Svelte, Solid, Astro, modern React with Vite) → Vitest: it reuses the already-configured Vite transform pipeline where Jest needs separate babel-jest / ts-jest setup.
  3. Otherwise (bundler-free Node service, React Native, CRA legacy) → Jest: the most ecosystem-supported choice.
  4. Legacy runners: maintaining a Mocha codebase → references/mocha.md; maintaining or migrating a Jasmine / Karma codebase → references/legacy-migration.md.

Step 1 - Install

Jest, per jest-start:

npm install --save-dev jest
# TypeScript - choose one:
npm install --save-dev ts-jest        # full type-checking; slower
npm install --save-dev babel-jest @babel/core @babel/preset-env @babel/preset-typescript
npm install --save-dev @jest/globals  # explicit imports instead of globals

babel-jest does NOT catch type errors - pair it with tsc --noEmit in CI. Scaffold config with npm init jest@latest.

Vitest, per vt-guide:

npm install -D vitest

If the project already has Vite + a vite.config.*, no extra config is needed.

Step 2 - First test

// sum.test.js (Jest - globals available by default)
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
// sum.test.js (Vitest - explicit imports required)
import { expect, test } from 'vitest'
import { sum } from './sum.js'

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3)
})

Wire package.json scripts:

{
  "scripts": {
    "test": "jest"
  }
}

or for Vitest - vitest with no subcommand is watch mode; vitest run is the single pass:

{
  "scripts": {
    "test": "vitest run",
    "test:watch": "vitest",
    "coverage": "vitest run --coverage"
  }
}

Step 3 - Configuration

Jest key settings (jest.config.js; full reference at jestjs.io/docs/configuration):

module.exports = {
  testEnvironment: 'jsdom',          // 'jsdom' for browser code; 'node' for backend
  testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'],
  transform: { '^.+\\.(ts|tsx)$': 'ts-jest' },
  collectCoverageFrom: ['src/**/*.{js,ts}', '!src/**/*.d.ts'],
  coverageThreshold: {
    global: { branches: 80, functions: 80, lines: 80, statements: 80 },
  },
  moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' },  // match tsconfig aliases
};

Gotcha: testEnvironment defaults to jsdom in Jest ≤26 but node from Jest 27+ - always set it explicitly.

Vitest reads vite.config.ts; add a test block via the vitest/config wrapper (full reference at vitest.dev/config):

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    environment: 'jsdom',       // 'jsdom' | 'node' | 'happy-dom' | 'edge-runtime'
    globals: false,             // prefer explicit imports over global injection
    setupFiles: ['./vitest.setup.ts'],
    coverage: {
      provider: 'v8',           // 'v8' (default) | 'istanbul'
      reporter: ['text', 'json', 'html', 'lcov'],
      thresholds: { lines: 80, functions: 80, branches: 80, statements: 80 },
      include: ['src/**'],
    },
  },
})

Step 4 - Mocking

Same three mock forms in both frameworks - jest.* in Jest, vi.* in Vitest (vitest.dev/api/vi; jestjs.io/docs/mock-functions):

// Standalone mock function
const myMock = jest.fn();            // Vitest: vi.fn()
myMock.mockReturnValue(42);

// Automatic module mock
jest.mock('./api-client');           // Vitest: vi.mock('./api-client', factor
Полный SKILL.md на GitHub

Установить js-unit-tests в Claude Code и Claude Desktop

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

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

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

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

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

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

Вложенные файлы

.tessl-plugin/plugin.jsonevals/alias-imports-unresolved-in-tests/criteria.jsonevals/alias-imports-unresolved-in-tests/task.mdevals/ci-job-hangs-and-ooms/criteria.jsonevals/ci-job-hangs-and-ooms/task.mdevals/coverage-gate-reports-95/criteria.jsonevals/coverage-gate-reports-95/task.mdevals/green-tests-that-cannot-fail/criteria.jsonevals/green-tests-that-cannot-fail/task.mdevals/in-source-tests-in-the-bundle/criteria.jsonevals/in-source-tests-in-the-bundle/task.mdevals/mailer-double-shared-across-files/criteria.jsonevals/mailer-double-shared-across-files/task.mdevals/node-tests-break-under-jsdom/criteria.jsonevals/node-tests-break-under-jsdom/task.mdevals/retry-test-hangs-on-fake-timers/criteria.jsonevals/retry-test-hangs-on-fake-timers/task.mdevals/snapshot-suite-never-fails/criteria.jsonevals/snapshot-suite-never-fails/task.mdevals/vitest-mock-per-test-return/criteria.jsonevals/vitest-mock-per-test-return/task.mdreferences/jest-coverage.mdreferences/legacy-migration.mdreferences/mocha.md

FAQ

Что делает скилл js-unit-tests?

Use for any question or task about JavaScript or TypeScript unit tests with Jest or Vitest, including quick how-to questions and tests for one function: mocking a module (jest.mock, vi.mock, vi.hoisted), spies and fake timers, path aliases that fail only in tests (`Cannot find module '@/...'`), coverage thresholds, watch mode and CI. Has authoring conventions and anti-patterns.

Как установить скилл js-unit-tests?

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

Скилл js-unit-tests запускает скрипты?

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

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

Сравнить js-unit-tests с