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★ 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:
expectmatchers, 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
- Match the existing convention first. A repo with
jest.config.*(or a"jest"package.json block) stays on Jest; one withvitest.config.*or atestblock invite.config.*stays on Vitest. Never mix two unit frameworks in one package. - 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-jestsetup. - Otherwise (bundler-free Node service, React Native, CRA legacy) → Jest: the most ecosystem-supported choice.
- 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
Установить js-unit-tests в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
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), без исполняемых скриптов.
Похожие скиллы
ci-review
The scan that the plugin's GitHub Action runs.
от Anthropicazure-static-web-apps
Helps create, configure, and deploy Azure Static Web Apps using the SWA CLI. Use when deploying static sites to Azure, setting up SWA local development…
от GitHubai-ready
Make any repo AI-ready — analyzes your codebase and generates AGENTS.md, copilot-instructions.md, CI workflows, issue templates, and more. Mines your PR…
от GitHubaws-cdk-python-setup
Setup and initialization guide for developing AWS CDK (Cloud Development Kit) applications in Python. This skill enables users to configure environment…
от GitHub