mcpbeat Sign in

Jest Unit Agent Skill

Unit testing skill using Jest for TypeScript and JavaScript, covering mocking, spies, snapshots, coverage, async testing, and custom matchers.

4k tokens
context cost
the whole folder, loaded on every use
1
files
instructions only
0
copies elsewhere
how many repositories repackaged it
195
stars on the repo
on the repository, not the skill itself

Install

one command, takes just this skill from the repository
npx skills add https://github.com/PramodDutta/qaskills --skill jest-unit

The instruction itself

20 sections, as written by the author

Jest Unit Testing Skill

You are an expert software engineer specializing in unit testing with Jest. When the user asks you to write, review, or debug Jest unit tests, follow these detailed instructions.

Core Principles

  • Test behavior, not implementation -- Tests should verify what code does, not how it does it.
  • One assertion focus per test -- Each test should verify a single logical concept.
  • Arrange-Act-Assert -- Structure every test into setup, execution, and verification.
  • Fast and isolated -- Unit tests must run in milliseconds and have no external dependencies.
  • Descriptive names -- Test names should read as specifications of the code's behavior.

Project Structure

src/
  services/
    user.service.ts
    user.service.test.ts
    order.service.ts
    order.service.test.ts
  utils/
    validators.ts
    validators.test.ts
    formatters.ts
    formatters.test.ts
  models/
    user.model.ts
  __mocks__/
    axios.ts
    database.ts
  __tests__/
    integration/
      user-order.test.ts
jest.config.ts

Configuration

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

const config: Config = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: ['<rootDir>/src'],
  testMatch: ['**/*.test.ts', '**/*.spec.ts'],
  collectCoverageFrom: [
    'src/**/*.ts',
    '!src/**/*.d.ts',
    '!src/**/*.test.ts',
    '!src/**/index.ts',
  ],
  coverageThresholds: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
  coverageReporters: ['text', 'lcov', 'json-summary'],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
  setupFilesAfterSetup: ['<rootDir>/jest.setup.ts'],
  clearMocks: true,
  restoreMocks: true,
};

export default config;

Writing Tests

Basic Test Structure

// validators.ts
export function isValidEmail(email: string): boolean {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

export function isStrongPassword(password: string): boolean {
  return (
    password.length >= 8 &&
    /[A-Z]/.test(password) &&
    /[a-z]/.test(password) &&
    /[0-9]/.test(password) &&
    /[!@#$%^&*]/.test(password)
  );
}
// validators.test.ts
import { isValidEmail, isStrongPassword } from './validators';

describe('isValidEmail', () => {
  it('should return true for valid email addresses', () => {
    expect(isValidEmail('[email protected]')).toBe(true);
    expect(isValidEmail('[email protected]')).toBe(true);
    expect(isValidEmail('[email protected]')).toBe(true);
  });

  it('should return false for invalid email addresses', () => {
    expect(isValidEmail('')).toBe(false);
    expect(isValidEmail('not-an-email')).toBe(false);
    expect(isValidEmail('@missing-local.com')).toBe(false);
    expect(isValidEmail('missing-at.com')).toBe(false);
    expect(isValidEmail('spaces [email protected]')).toBe(false);
  });
});

describe('isStrongPassword', () => {
  it('should accept a strong password', () => {
    expect(isStrongPassword('SecurePass1!')).toBe(true);
  });

  it('should reject passwords shorter than 8 characters', () => {
    expect(isStrongPassword('Ab1!')).toBe(false);
  });

  it('should reject passwords without uppercase letters', () => {
    expect(isStrongPassword('lowercase1!')).toBe(false);
  });

  it('should reject passwords without lowercase letters', () => {
    expect(isStrongPassword('UPPERCASE1!')).toBe(false);
  });

  it('should reject passwords without numbers', () => {
    expect(isStrongPassword('NoNumbers!')).toBe(false);
  });

  it('should reject passwords without special characters', () => {
    expect(isStrongPassword('NoSpecial1')).toBe(false);
  });
});

Testing Classes and Services

// user.service.ts
import { UserRepository } from './user.repository';
import { EmailService } from './email.service';

export class UserService {
  constructor(
    private userRepo: UserRepository,
    private emailService: EmailService
  ) {}

  async createUser(email: string, name: string): Promise<User> {
    const existing = await this.userRepo.findByEmail(email);
    if (existing) {
      throw new Error('User already exists');
    }

    const user = await this.userRepo.create({ email, name });
    await this.emailService.sendWelcomeEmail(user.email, user.name);
    return user;
  }

  async getUser(id: string): Promise<User | null> {
    return this.userRepo.findById(id);
  }

  async deleteUser(id: string): Promise<void> {
    const user = await this.userRepo.findById(id);
    if (!user) {
      throw new Error('User not found');
    }
    await this.userRepo.delete(id);
  }
}
// user.service.test.ts
import { UserService } from './user.service';
import { UserRepository } from './user.repository';
import { EmailService } from './email.service';

// Mock the dependencies
jest.mock('./user.repository');
jest.mock('./email.service');

describe('UserService', () => {
  let userService: UserService;
  let mockUserRepo: jest.Mocked<UserRepository>;
  let mockEmailService: jest.Mocked<EmailService>;

  beforeEach(() => {
    mockUserRepo = new UserRepository() as jest.Mocked<UserRepository>;
    mockEmailService = new EmailService() as jest.Mocked<EmailService>;
    userService = new UserService(mockUserRepo, mockEmailService);
  });

  describe('createUser', () => {
    it('should create a user and send welcome email', async () => {
      const newUser = { id: '1', email: '[email protected]', name: 'New User' };
      mockUserRepo.findByEmail.mockResolvedValue(null);
      mockUserRepo.create.mockResolvedValue(newUser);
      mockEmailService.sendWelcomeEmail.mockResolvedValue(undefined);

      const result = await userService.createUser('[email protected]', 'New User');

      expect(result).toEqual(newUser);
      expect(mockUserRepo.findByEmail).toHaveBeenCalledWith('[email protected]');
      expect(mockUserRepo.create).toHaveBeenCalledWith({
        email: '[email protected]',
        name: 'New User',
      });
      expect(mockEmailService.sendWelcomeEmail).toHaveBeenCalledWith(
        '[email protected]',
        'New User'
      );
    });

    it('should throw error if user already exists', async () => {
      mockUserRepo.findByEmail.mockResolvedValue({
        id: '1',
        email: '[email protected]',
        name: 'Existing',
      });

      await expect(
        userService.createUser('[email protected]', 'Duplicate')
      ).rejects.toThrow('User already exists');

      expect(mockUserRepo.create).not.toHaveBeenCalled();
      expect(mockEmailService.sendWelcomeEmail).not.toHaveBeenCalled();
    });
  });

  describe('getUser', () => {
    it('should return user when found', async () => {
      const user = { id: '1', email: '[email protected]', name: 'User' };
      mockUserRepo.findById.mockResolvedValue(user);

      const result = await userService.getUser('1');

      expect(result).toEqual(user);
      expect(mockUserRepo.findById).toHaveBeenCalledWith('1');
    });

    it('should return null when user not found', async () => {
      mockUserRepo.findById.mockResolvedValue(null);

      const result = await userService.getUser('nonexistent');

      expect(result).toBeNull();
    });
  });

  describe('deleteUser', () => {
    it('should delete an existing user', async () => {
      const user = { id: '1', email: '[email protected]', name: 'User' };
      mockUserRepo.findById.mockResolvedValue(user);
      mockUserRepo.delete.mockResolvedValue(undefined);

      await userService.deleteUser('1');

      expect(mockUserRepo.delete).toHaveBeenCalledWith('1');
    });

    it('should throw error when deleting non-existent user', async () => {
      mockUserRepo.findById.mockResolvedValue(null);

      await expect(userService.deleteUser('nonexistent')).rejects.toThrow(
        'User not found'
      );
    });
  });
});

Mocking Patterns

Manual Mocks

// __mocks__/axios.ts
const axios = {
  get: jest.fn(() => Promise.resolve({ data: {} })),
  post: jest.fn(() => Promise.resolve({ data: {} })),
  put: jest.fn(() => Promise.resolve({ data: {} })),
  delete: jest.fn(() => Promise.resolve({ data: {} })),
  create: jest.fn(function () {
    return axios;
  }),
  interceptors: {
    request: { use: jest.fn() },
    response: { use: jest.fn() },
  },
};

export default axios;

Spying on Methods

it('should call console.error on failure', async () => {
  const consoleSpy = jest.spyOn(console, 'error').mockImplementation();

  await processData(invalidData);

  expect(consoleSpy).toHaveBeenCalledWith(
    expect.stringContaining('Processing failed')
  );

  consoleSpy.mockRestore();
});

Mocking Timers

describe('Debounce function', () => {
  beforeEach(() => {
    jest.useFakeTimers();
  });

  afterEach(() => {
    jest.useRealTimers();
  });

  it('should debounce function calls', () => {
    const fn = jest.fn();
    const debounced = debounce(fn, 300);

    debounced();
    debounced();
    debounced();

    expect(fn).not.toHaveBeenCalled();

    jest.advanceTimersByTime(300);

    expect(fn).toHaveBeenCalledTimes(1);
  });

  it('should reset timer on subsequent calls', () => {
    const fn = jest.fn();
    const debounced = debounce(fn, 300);

    debounced();
    jest.advanceTimersByTime(200);
    debounced(); // resets the timer
    jest.advanceTimersByTime(200);

    expect(fn).not.toHaveBeenCalled();

    jest.advanceTimersByTime(100);
    expect(fn).toHaveBeenCalledTimes(1);
  });
});

Mocking Modules

// Mock an entire module
jest.mock('fs', () => ({
  readFileSync: jest.fn(() => 'mocked content'),
  writeFileSync: jest.fn(),
  existsSync: jest.fn(() => true),
}));

// Mock with factory function
jest.mock('./config', () => ({
  getConfig: () => ({
    apiUrl: 'http://test-api.example.com',
    timeout: 1000,
  }),
}));

// Partial mock -- keep some original implementations
jest.mock('./utils', () => ({
  ...jest.requireActual('./utils'),
  fetchData: jest.fn(),
}));

Async Testing

// Testing resolved promises
it('should resolve with data', async () => {
  const result = await fetchUser('1');
  expect(result.name).toBe('John');
});

// Testing rejected promises
it('should reject with error', async () => {
  await expect(fetchUser('invalid')).rejects.toThrow('Not found');
});

// Testing callbacks
it('should call callback with data', (done) => {
  fetchUserCallback('1', (err, data) => {
    expect(err).toBeNull();
    expect(data.name).toBe('John');
    done();
  });
});

// Testing event emitters
it('should emit data event', (done) => {
  const emitter = new DataEmitter();
  emitter.on('data', (payload) => {
    expect(payload).toEqual({ id: 1 });
    done();
  });
  emitter.start();
});

Snapshot Testing

// Component snapshot
it('should render correctly', () => {
  const output = renderComponent({ name: 'Test', count: 5 });
  expect(output).toMatchSnapshot();
});

// Inline snapshot
it('should format user display name', () => {
  const result = formatDisplayName({ first: 'John', last: 'Doe' });
  expect(result).toMatchInlineSnapshot(`"John Doe"`);
});

// Custom serializer
expect.addSnapshotSerializer({
  test: (val) => val instanceof Date,
  print: (val) => `Date(${(val as Date).toISOString()})`,
});

Custom Matchers

// jest.setup.ts
expect.extend({
  toBeWithinRange(received: number, floor: number, ceiling: number) {
    const pass = received >= floor && received <= ceiling;
    return {
      pass,
      message: () =>
        `expected ${received} to be within range ${floor} - ${ceiling}`,
    };
  },

  toBeValidEmail(received: string) {
    const pass = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(received);
    return {
      pass,
      message: () => `expected "${received}" to be a valid email address`,
    };
  },

  toContainObject(received: any[], expected: Record<string, any>) {
    const pass = received.some((item) =>
      Object.entries(expected).every(([key, value]) => item[key] === value)
    );
    return {
      pass,
      message: () =>
        `expected array to contain object matching ${JSON.stringify(expected)}`,
    };
  },
});

// Type declaration
declare global {
  namespace jest {
    interface Matchers<R> {
      toBeWithinRange(floor: number, ceiling: number): R;
      toBeValidEmail(): R;
      toContainObject(expected: Record<string, any>): R;
    }
  }
}

Test Utilities

Test Data Helpers

export function createMockUser(overrides: Partial<User> = {}): User {
  return {
    id: '1',
    email: '[email protected]',
    name: 'Test User',
    role: 'user',
    createdAt: '2024-01-01T00:00:00Z',
    ...overrides,
  };
}

export function createMockResponse<T>(data: T, status = 200) {
  return {
    data,
    status,
    headers: {},
    config: {},
    statusText: 'OK',
  };
}

Best Practices

  • One logical assertion per test -- Multiple expect calls are fine if they verify one concept.
  • Use describe blocks to organize tests by method or feature.
  • Name tests as specifications -- it('should return null when user not found').
  • Mock at the boundary -- Mock external services, not internal functions.
  • Use beforeEach for setup -- Ensure clean state for every test.
  • Set clearMocks: true in config -- Automatically clear mock state between tests.
  • Prefer mockResolvedValue over mockImplementation for simple returns.
  • Test edge cases -- Empty strings, null, undefined, zero, negative numbers.
  • Keep tests fast -- A slow unit test is usually testing too much.

10. Maintain coverage thresholds -- Set minimums and enforce in CI.

Anti-Patterns to Avoid

  • Testing implementation details -- Refactoring should not break tests.
  • Excessive mocking -- If you mock everything, you test nothing.
  • Shared mutable state -- Never use let variables modified across tests without beforeEach.
  • Testing private methods directly -- Test through the public API.
  • Snapshot abuse -- Do not snapshot large objects; the diff becomes meaningless.
  • No assertions -- A test without expect() always passes and tests nothing.
  • Ignoring test failures -- Never use test.skip or .only in committed code.
  • Testing framework code -- Do not test that Array.map works.
  • Giant test files -- Keep test files focused and under 300 lines.

10. Not testing error paths -- The catch/error branches need testing too.

Running Tests

# Run all tests
npx jest

# Run specific file
npx jest src/services/user.service.test.ts

# Run tests matching pattern
npx jest --testPathPattern="user"

# Run with coverage
npx jest --coverage

# Watch mode
npx jest --watch

# Run only changed files
npx jest --onlyChanged

# Verbose output
npx jest --verbose

Other skills for the same job

different authors, same section of the catalogue
Webapp Testing
by anthropics
vendor ×12

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

6k tokens scripts
Finishing A Development Branch
by ZhanlinCui
×7

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup

1k tokens
Test Driven Development
by w95
×7

Use when implementing any feature or bugfix, before writing implementation code

2k tokens
Systematic Debugging
by ratacat
×7

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes

10k tokens scripts
Verification Before Completion
by ZhanlinCui
×6

Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always

1k tokens
Backtest Expert
by BaggaT236
×3

Expert guidance for systematic backtesting of trading strategies. Use when developing, testing, stress-testing, or validating quantitative trading strategies. Covers "beating ideas to death" methodology, parameter robustness testing, slippage modeling, bias prevention, and interpreting backtest results. Applicable when user asks about backtesting, strategy validation, robustness testing, avoiding overfitting, or systematic trading development.

15k tokens scripts
Adaptyv
by christophacham
×3

Cloud laboratory platform for automated protein testing and validation. Use when designing proteins and needing experimental validation including binding assays, expression testing, thermostability measurements, enzyme activity assays, or protein sequence optimization. Also use for submitting experiments via API, tracking experiment status, downloading results, optimizing protein sequences for better expression using computational tools (NetSolP, SoluProt, SolubleMPNN, ESM), or managing protein design workflows with wet-lab validation.

16k tokens
Aeon
by christophacham
×3

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

19k tokens

How to use it

Copy the folder

Take pramoddutta/jest-unit from the repository into ~/.claude/skills for personal use, or into .claude/skills inside a project.

Check the name does not clash

The agent identifies a skill by the name field in its header. Two skills with the same name cannot sit side by side — one of them will be ignored.

Install what it needs

The instructions reference npx. Without those the skill loads but fails at the first command.