Command Palette

Search for a command to run...

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

jest

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

Jest is a JavaScript and TypeScript testing framework from the OpenJS Foundation that bundles a test runner, assertions, mocking, snapshots and code coverage…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

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

Jest — JavaScript Testing Framework

Overview

Jest ships a test runner, expect assertions, mocks, snapshots and Istanbul coverage in one package. Current major version is 30 (needs Node 18.14+, 20, 22 or 24+). This skill covers setup for TypeScript, writing tests, mocking, async code, snapshots, coverage and CI.

Instructions

Install and configure (TypeScript)

npm install --save-dev jest ts-jest typescript @types/jest ts-node

ts-node is needed only so Jest can read jest.config.ts. ts-jest 29.x supports Jest 29 and 30.

// jest.config.ts
import type { Config } from 'jest';

const config: Config = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: ['<rootDir>/src'],
  collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts', '!src/**/index.ts'],
  coverageThreshold: {
    global: { branches: 80, functions: 80, lines: 80, statements: 80 },
  },
  moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' },
};

export default config;

The key is coverageThreshold (singular). A misspelling such as coverageThresholds only prints a validation warning, and no threshold is enforced.

TypeScript 6 no longer loads every @types/* package automatically, so without a types entry the globals describe, test, expect and jest fail with "Cannot find name". Either list them in tsconfig.json or import from @jest/globals in each test:

{ "compilerOptions": { "target": "es2022", "module": "commonjs", "esModuleInterop": true, "strict": true, "types": ["jest", "node"] } }

Scripts:

{ "scripts": { "test": "jest", "test:watch": "jest --watch", "test:coverage": "jest --coverage" } }

Test files match **/__tests__/**/*.[jt]s?(x) and **/?(*.)+(spec|test).[jt]s?(x) by default. Without ts-jest, @swc/jest is a faster transformer and babel-jest is built in.

Assertions

// src/math.test.ts
import { add, divide, createUser } from './math';

describe('math', () => {
  test('adds two numbers', () => {
    expect(add(2, 3)).toBe(5);
  });

  test('toEqual compares deeply, toBe compares identity', () => {
    expect(createUser('Alice', 30)).toEqual({ name: 'Alice', age: 30, id: expect.any(String) });
  });

  test('throws on division by zero', () => {
    expect(() => divide(10, 0)).toThrow('Cannot divide by zero');
  });
});

Mocks

// src/userService.test.ts
import { UserService } from './userService';
import { database } from './database';

jest.mock('./database'); // auto-mock every export

const mockedDb = jest.mocked(database);

beforeEach(() => jest.clearAllMocks());

test('fetches a user by id', async () => {
  mockedDb.findById.mockResolvedValue({ id: '1', name: 'Alice' });

  const user = await new UserService().getUser('1');

  expect(mockedDb.findById).toHaveBeenCalledWith('1');
  expect(user.name).toBe('Alice');
});

test('rejects when the user is missing', async () => {
  mockedDb.findById.mockResolvedValue(null);
  await expect(new UserService().getUser('999')).rejects.toThrow('User not found');
});
  • jest.fn() makes a standalone mock; .mockReturnValueOnce(), .mockResolvedValue() and .mockImplementation() control it.
  • jest.spyOn(obj, 'method') wraps a real method; mockRestore() puts it back.
  • clearAllMocks resets call history, resetAllMocks also removes implementations, restoreAllMocks restores spies. Config keys clearMocks, resetMocks and restoreMocks do this before every test.

Async code and timers

Always await or return the promise, otherwise the test ends before the assertion runs.

test('retries a failed fetch', async () => {
  global.fetch = jest.fn().mockRejectedValue(new Error('Network error'));

  const result = await fetchWithRetry('/api/orders', { retries: 3 });

  expect(result.error).toBe('Network error');
  expect(global.fetch).toHaveBeenCalledTimes(4); // first call + 3 retries
});

test('debounced search fires once', () => {
  jest.useFakeTimers();
  const onSearch = jest.fn();
  const search = debounce(onSearch, 300);

  search('jest'); search('jest co');
  jest.advanceTimersByTime(300);

  expect(onSearch).toHaveBeenCalledTimes(1);
  jest.useRealTimers();
});

Snapshots

import { render } from '@testing-library/react';
import { UserCard } from './UserCard';

test('renders the admin card', () => {
  const { container } = render(<UserCard name="Alice Johnson" role="admin" />);
  expect(container).toMatchSnapshot();
});

test('formats an address', () => {
  expect(formatAddress({ street: '123 Main St', city: 'Springfield', state: 'IL' }))
    .toMatchInlineSnapshot(`"123 Main St, Springfield, IL"`);
});

Update intentionally changed snapshots with npx jest --updateSnapshot (-u). Review the snapshot diff in the pull request like any code.

React component tests need testEnvironment: 'jsdom' and, since Jest 28, a separate package: `npm install --save-dev jest-environment-jsdom @testing-libr

Полный SKILL.md на GitHub

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

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

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

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

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

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

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

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

_scores.json

FAQ

Что делает скилл jest?

Jest is a JavaScript and TypeScript testing framework from the OpenJS Foundation that bundles a test runner, assertions, mocking, snapshots and code coverage in one package. Use it when you need to write unit tests, mock modules or timers, test async code, enforce coverage thresholds, run tests in watch mode, or wire Jest into CI for Node.js, React or TypeScript projects.

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

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

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

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

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

Сравнить jest с