Skip to main content
skill CX Codex

jest-generator — Claude Code skill: what it does, how to install

Generates Jest unit tests for JavaScript, TypeScript, and React components. Sets up mocks, spies, and async assertions while targeting 80% test coverage.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add secondsky/claude-skills --skill jest-generator -a claude-code
Open on GitHub

What jest-generator does

The skill creates test files alongside source code following the <module>.test.ts or .test.tsx naming pattern. It structures test suites using Arrange-Act-Assert blocks inside describe closures. To prevent state leaks between tests, it cleans up mocks via beforeEach and afterEach hooks using jest.clearAllMocks() and jest.restoreAllMocks().

Generated suites account for happy paths, edge cases, and error throwing. The skill handles module mocking through jest.mock(), tracks method calls with jest.spyOn(), fast-forwards simulated clocks with jest.useFakeTimers(), and verifies async rejections. For test execution, it suggests running bun test for speed or npm test as a fallback.

Component tests rely directly on @testing-library/react and @testing-library/jest-dom. If your project lacks these dependencies, the generated UI tests will fail to run.

What it helps with

  • generate Jest unit tests for TypeScript modules
  • mock external APIs and dependencies with jest.mock
  • test React component interactions and button clicks
  • advance simulated clocks using fake timer controls
  • raise code coverage to meet the 80% target

Example prompts for the agent

  • Generate Jest tests for src/utils/validator.ts including edge cases
  • Write unit tests for src/components/Button.tsx and verify click events
  • Add async tests with fake timers for src/models/User.ts

How to install jest-generator

1Skills CLI (Vercel)

npx skills add secondsky/claude-skills --skill jest-generator -a claude-code

2Manually: put the files in place

~/.claude/skills/jest-generator/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/jest-generator/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about jest-generator

How do I install jest-generator in Claude Code?

Run npx skills add secondsky/claude-skills --skill jest-generator -a claude-code. You can also manually add the skill file at ~/.claude/skills/jest-generator/SKILL.md.

What does jest-generator do?

It guides coding agents to produce clean Jest unit tests for JavaScript, TypeScript, and React codebases. It enforces proper suite structures, isolation hooks, error assertions, and external mocks.

Which test runner does jest-generator recommend?

The skill prefers bun test for faster runs, with npm test provided as an alternative. It includes standard commands for single files, watch mode, and code coverage reports.

Source text

SKILL.md · MIT
---
name: jest-generator
description: Generate Jest unit tests for JavaScript/TypeScript with mocking, coverage. Use for JS/TS modules, React components, test generation, or encountering missing coverage, improper mocking, test structure errors.
allowed-tools: Read, Write, Edit, Bash, Grep, Glob
license: MIT
---

# Jest Generator Skill

## Purpose

Generate Jest-based unit tests for JavaScript and TypeScript code, following Jest conventions and best practices with proper mocking, describe blocks, and code organization.

## When to Use

- Generate Jest tests for JavaScript/TypeScript modules
- Create test files for React components
- Add missing test coverage to existing code
- Need Jest-specific patterns (mocks, spies, snapshots)

## Test File Naming

**Source to Test Mapping:**
- `src/components/Feature.tsx` → `src/components/Feature.test.tsx`
- `src/utils/validator.ts` → `src/utils/validator.test.ts`
- `src/models/User.ts` → `src/models/User.test.ts`

## Running Tests

```bash
# Preferred: Using bun (faster)
bun test

# Run specific file
bun test src/utils/validator.test.ts

# Run with coverage
bun test --coverage

# Watch mode
bun test --watch

# Alternative: Using npm
npm test
npm test -- --coverage
```

## Jest Test Structure

```typescript
import { functionToTest, ClassToTest } from './Feature'

jest.mock('./dependency')

describe('ModuleName', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  afterEach(() => {
    jest.restoreAllMocks()
  })

  describe('ClassName', () => {
    let instance: ClassToTest

    beforeEach(() => {
      instance = new ClassToTest()
    })

    it('should return expected result with valid input', () => {
      // Arrange
      const input = { key: 'value' }
      const expected = { processed: true }

      // Act
      const result = instance.method(input)

      // Assert
      expect(result).toEqual(expected)
    })

    it('should throw error with invalid input', () => {
      expect(() => instance.method(null)).toThrow('Invalid input')
    })
  })
})
```

## Jest-Specific Patterns

### Mocking

```typescript
// Mock entire module
jest.mock('./api', () => ({
  fetchData: jest.fn(),
}))

// Mock with implementation
const mockFn = jest.fn((x: number) => x * 2)

// Spy on method
const spy = jest.spyOn(obj, 'method').mockReturnValue('mocked')
spy.mockRestore()
```

### Async Testing

```typescript
it('should resolve with data', async () => {
  const result = await asyncFunction()
  expect(result).toBeDefined()
})

it('should reject with error', async () => {
  await expect(asyncFunction()).rejects.toThrow('Error')
})
```

### Timers

```typescript
beforeEach(() => jest.useFakeTimers())
afterEach(() => jest.useRealTimers())

it('should execute after timeout', () => {
  const callback = jest.fn()
  setTimeout(callback, 1000)
  jest.advanceTimersByTime(1000)
  expect(callback).toHaveBeenCalled()
})
```

### Common Matchers

```typescript
// Equality
expect(value).toBe(expected)
expect(value).toEqual(expected)

// Truthiness
expect(value).toBeTruthy()
expect(value).toBeNull()
expect(value).toBeDefined()

// Arrays/Objects
expect(array).toContain(item)
expect(obj).toHaveProperty('key')

// Functions/Promises
expect(fn).toThrow('error')
await expect(promise).resolves.toBe(value)

// Mock functions
expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledWith(arg)
```

### React Component Testing

```typescript
import { render, screen, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom'
import { Button } from './Button'

describe('Button', () => {
  it('should call onClick when clicked', () => {
    const handleClick = jest.fn()
    render(<Button onClick={handleClick}>Click me</Button>)
    fireEvent.click(screen.getByText('Click me'))
    expect(handleClick).toHaveBeenCalledTimes(1)
  })
})
```

## Quality Checklist

- [ ] Test file properly named (`<module>.test.ts`)
- [ ] All exported functions/classes tested
- [ ] Happy path and edge cases included
- [ ] Error conditions tested
- [ ] External dependencies mocked
- [ ] Tests organized with describe blocks
- [ ] beforeEach/afterEach for setup/cleanup
- [ ] Descriptive test names
- [ ] Coverage ≥ 80%

## Best Practices

1. Use descriptive test names: `should <expected> when <condition>`
2. Organize with describe blocks
3. Mock external dependencies only
4. Test user behavior for components
5. Use test.each for parametrized tests
6. Keep tests independent
7. Test error conditions
8. Aim for 80%+ coverage

© secondsky · MIT · secondsky/claude-skills

Similar skills

All skills for Testing and QA →

From the same set128

model-deployment A skill for getting a trained model into production: FastAPI server, Docker, Kubernetes, monitoring and drift detection. Useful once the model works and serving does not. CX Codex +1 379installs cloudflare-agents A skill for building AI agents on Cloudflare Workers with tools, MCP and LLM providers. Useful when the agent runs inside a worker. CX Codex +1 378installs react-hook-form-zod Sets up type-safe React forms using React Hook Form and Zod validation. It helps with schema definitions, nested field arrays, and server validation. CX Codex +1 376installs cloudflare-mcp-server A skill for building MCP servers on Cloudflare Workers: tools, resources, prompts and transport choices. Useful when you write your own server for an AI agent. CX Codex +1 375installs thesys-generative-ui A skill that teaches your agent to build React components from plain-language prompts with the Thesys SDK. Handy when you want a UI sketched out from a description. CX Codex +1 371installs nuxt-studio Sets up the Nuxt Studio visual editor for Nuxt Content sites. It guides OAuth authentication setup and deployment to subdomains via Cloudflare. CX Codex +1 368installs maz-ui This skill teaches your agent Maz-UI v4: 50+ components, composables and directives for Vue 3 and Nuxt 3. Handy when you build forms, dialogs or data tables. CX Codex +1 369installs woocommerce-code-review Audits WooCommerce code changes against core engineering standards and copy rules. Useful during local reviews and PR preparation. CX Codex +1 366installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor