AGENT SKILL

generating-unit-tests

Test automatically generate comprehensive unit tests from source code covering happy paths, edge cases, and error conditions. Use when creating test coverage for functions, classes, or modules. Trigger with phrases like "generate unit tests", "create tests for", or "add test coverage".

License 许可
MIT
最近更新
2026-07-13
Stars
★ 1
Forks
0

01 前言 Front Matter

name
generating-unit-tests
tags
[ "testing", "unit-tests" ]
author
Jeremy Longshore <jeremy@intentsolutions.io>
license
MIT
version
1.0.0
description
Test automatically generate comprehensive unit tests from source code covering happy paths, edge cases, and error conditions. Use when creating test coverage for functions, classes, or modules. Trigger with phrases like "generate unit tests", "create tests for", or "add test coverage".
allowed-tools
Read, Write, Edit, Grep, Glob, Bash(test:unit-*)
compatible-with
claude-code, codex, openclaw

03 SKILL.md 正文

Unit Test Generator

Overview

Automatically generate comprehensive unit tests from source code analysis covering happy paths, edge cases, boundary conditions, and error handling. Supports Jest, Vitest, Mocha (JavaScript/TypeScript), pytest (Python), JUnit 5 (Java), and Go testing with testify.

Prerequisites

  • Testing framework installed and configured (jest, vitest, pytest, junit-jupiter, or Go testing)
  • Source code with clear function signatures, type annotations, or JSDoc comments
  • Test directory structure established (__tests__/, tests/, spec/, or *_test.go)
  • Mocking library available (jest.mock, unittest.mock, Mockito, or gomock)
  • Package scripts configured to run tests (npm test, pytest, go test)

Instructions

  1. Scan the codebase with Glob to locate source files that lack corresponding test files (e.g., src/utils/parser.ts without __tests__/parser.test.ts).
  2. Read each untested source file and extract:
    • All exported functions and class methods with their signatures.
    • Parameter types, return types, and thrown exceptions.
    • External dependencies (imports from other modules, third-party libraries, I/O).
    • Pure vs. impure function classification.
  3. For each function, generate test cases in these categories:
    • Happy path: Valid inputs producing expected outputs (at least 2 cases).
    • Edge cases: Empty strings, empty arrays, zero, negative numbers, null, undefined, maximum values.
    • Error conditions: Invalid types, missing required fields, network failures, permission errors.
    • Boundary values: Off-by-one, integer overflow, string length limits.
  4. Create mock declarations for all external dependencies:
    • Database calls return predictable fixture data.
    • HTTP clients return canned responses with configurable status codes.
    • File system operations use in-memory buffers or temp directories.
  5. Write the test file following project conventions:
    • Match the existing test file naming pattern (*.test.ts, *.spec.js, test_*.py).
    • Group tests in describe/context blocks by function name.
    • Use beforeEach/afterEach for setup and teardown.
    • Include inline comments explaining non-obvious test rationale.
  6. Run the generated tests to verify they pass, then check coverage to confirm the target function is fully exercised.
  7. Report coverage gaps and suggest additional test cases for uncovered branches.

Output

  • Test files placed alongside source files or in the project's test directory
  • Mock/stub files for external dependencies
  • Coverage report showing line, branch, and function coverage for tested modules
  • List of remaining coverage gaps with suggested test cases

Error Handling

Error Cause Solution
Cannot find module on import Test file path does not match project module resolution Check tsconfig.json paths and moduleNameMapper in Jest config
Mock not intercepting calls Mock defined after module import caches the real implementation Move jest.mock() calls to the top of the file before any imports
Async test timeout Promise never resolves due to missing await or unhandled rejection Add await before async calls; increase timeout with jest.setTimeout()
Tests pass alone but fail together Shared mutable state leaking between tests Reset state in afterEach; avoid module-level variables; use jest.isolateModules()
Snapshot mismatch on first run No existing snapshot baseline Run with --updateSnapshot on first execution to create the baseline

Examples

Jest test for a string utility:

import { slugify } from '../src/utils/slugify';

describe('slugify', () => {
  it('converts spaces to hyphens', () => {
    expect(slugify('hello world')).toBe('hello-world');
  });
  it('lowercases all characters', () => {
    expect(slugify('Hello World')).toBe('hello-world');
  });
  it('removes special characters', () => {
    expect(slugify('hello@world!')).toBe('helloworld');
  });
  it('handles empty string', () => {
    expect(slugify('')).toBe('');
  });
  it('trims leading and trailing whitespace', () => {
    expect(slugify('  spaced  ')).toBe('spaced');
  });
});

pytest test for a data validator:

import pytest
from myapp.validators import validate_email

class TestValidateEmail:
    def test_accepts_valid_email(self):
        assert validate_email("user@example.com") is True

    def test_rejects_missing_at_sign(self):
        assert validate_email("userexample.com") is False

    def test_rejects_empty_string(self):
        assert validate_email("") is False

    def test_rejects_none(self):
        with pytest.raises(TypeError):
            validate_email(None)

Resources

04 同仓库更多 Skills

jukeyman
jukeyman/jukeyman-skills

zustand-store-creator

Create zustand store creator operations. Auto-activating skill for Frontend Development. Triggers on: zustand store creator, zustand store creator Part of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like "zustand store creator", "zustand creator", "zustand".

★ 1
jukeyman
jukeyman/jukeyman-skills

zero-trust-config-helper

Configure with zero trust config helper operations. Auto-activating skill for Security Advanced. Triggers on: zero trust config helper, zero trust config helper Part of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like "zero trust config helper", "zero helper", "zero".

★ 1
jukeyman
jukeyman/jukeyman-skills

zapier-integration-helper

Assist with zapier integration helper operations. Auto-activating skill for Business Automation. Triggers on: zapier integration helper, zapier integration helper Part of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like "zapier integration helper", "zapier helper", "zapier".

★ 1
jukeyman
jukeyman/jukeyman-skills

yaml-config-validator

Validate yaml config validator operations. Auto-activating skill for DevOps Basics. Triggers on: yaml config validator, yaml config validator Part of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like "yaml config validator", "yaml validator", "yaml".

★ 1
jukeyman
jukeyman/jukeyman-skills

xvary-stock-research

Thesis-driven equity analysis from public SEC EDGAR and market data; /analyze, /score, /compare workflows with bundled Python tools (Claude Code, Cursor, Codex).

★ 1
jukeyman
jukeyman/jukeyman-skills

xss-vulnerability-scanner

Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals. Triggers on: xss vulnerability scanner, xss vulnerability scanner Part of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like "xss vulnerability scanner", "xss scanner", "xss".

★ 1