本文へ移動
cccskills
無料GitHub で公開

snapshot-test-refactorer

Refactors brittle snapshot tests into resilient, focused assertions. Provides strategies for reducing snapshot size, extracting meaningful assertions, and maintaining snapshots. Use for "snapshot testing", "snapshot refactoring", "brittle tests", or "assertion improvement".

インストール方法を見る

含まれるファイル(1)

  • SKILL.md8.8 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Snapshot Test Refactorer

Replace brittle snapshots with meaningful, maintainable assertions.

Problems with Snapshot Tests

// ❌ Bad: Full component snapshot
test("renders UserProfile", () => {
  const { container } = render(<UserProfile user={mockUser} />);
  expect(container).toMatchSnapshot();
});

// Problems:
// 1. Fails on any change (even whitespace)
// 2. No clear intent
// 3. Hard to review diffs
// 4. Doesn't test behavior
// 5. Implementation coupled

Refactoring Strategy

// ✅ Good: Specific assertions
test("renders UserProfile with user data", () => {
  render(<UserProfile user={mockUser} />);

  // Test what matters
  expect(screen.getByText(mockUser.name)).toBeInTheDocument();
  expect(screen.getByText(mockUser.email)).toBeInTheDocument();
  expect(screen.getByRole("img")).toHaveAttribute("src", mockUser.avatar);
});

test("shows edit button for own profile", () => {
  render(<UserProfile user={mockUser} isOwnProfile={true} />);

  expect(
    screen.getByRole("button", { name: "Edit Profile" })
  ).toBeInTheDocument();
});

test("hides edit button for other profiles", () => {
  render(<UserProfile user={mockUser} isOwnProfile={false} />);

  expect(
    screen.queryByRole("button", { name: "Edit Profile" })
  ).not.toBeInTheDocument();
});

Inline Snapshots for Data

// ❌ Bad: External snapshot file
test("formats user data", () => {
  const result = formatUser(mockUser);
  expect(result).toMatchSnapshot();
});

// ✅ Good: Inline snapshot (visible in code)
test("formats user data", () => {
  const result = formatUser(mockUser);
  expect(result).toMatchInlineSnapshot(`
    {
      "displayName": "John Doe",
      "initials": "JD",
      "memberSince": "2020-01-01",
    }
  `);
});

Partial Snapshots

// ❌ Bad: Snapshot entire API response
test("fetches user", async () => {
  const response = await api.getUser("123");
  expect(response).toMatchSnapshot();
});

// ✅ Good: Test important parts
test("fetches user with required fields", async () => {
  const response = await api.getUser("123");

  expect(response).toMatchObject({
    id: "123",
    email: expect.stringContaining("@"),
    role: expect.any(String),
  });

  // Snapshot only stable, important data
  expect({
    name: response.name,
    role: response.role,
  }).toMatchInlineSnapshot(`
    {
      "name": "John Doe",
      "role": "USER",
    }
  `);
});

Serializer for Unstable Data

// Remove unstable fields before snapshot
expect.addSnapshotSerializer({
  test: (val) => val && typeof val === "object" && "createdAt" in val,
  serialize: (val) => {
    const { createdAt, updatedAt, ...rest } = val;
    return JSON.stringify(rest, null, 2);
  },
});

// Now timestamps won't break tests
test("creates user", async () => {
  const user = await createUser({ name: "Test" });

  expect(user).toMatchInlineSnapshot(`
    {
      "id": "123",
      "name": "Test",
      "role": "USER"
    }
  `);
  // createdAt automatically removed
});

Snapshot Trimming Strategy

// Before: 500 line snapshot
expect(component).toMatchSnapshot();

// After: Focus on critical parts
const criticalElements = {
  header: screen.getByRole("banner").textContent,
  mainAction: screen.getByRole("button", { name: /submit/i }).textContent,
  errorMessage: screen.queryByRole("alert")?.textContent,
};

expect(criticalElements).toMatchInlineSnapshot(`
  {
    "errorMessage": null,
    "header": "Welcome",
    "mainAction": "Submit",
  }
`);

Visual Regression Alternative

// Instead of DOM snapshot, use visual regression
test("Profile component appearance", async ({ page }) => {
  await page.goto("/profile");

  // Visual snapshot (Playwright)
  await expect(page).toHaveScreenshot("profile.png", {
    maxDiffPixels: 100,
  });
});

When Snapshots Are Acceptable

// ✅ OK: Error messages (rarely change)
test("validates email format", () => {
  const errors = validateEmail("invalid");
  expect(errors).toMatchInlineSnapshot(`
    [
      "Email must contain @",
      "Email must contain domain",
    ]
  `);
});

// ✅ OK: API response structure (stable contract)
test("user API response structure", async () => {
  const response = await api.getUser("123");

  expect(Object.keys(response).sort()).toMatchInlineSnapshot(`
    [
      "createdAt",
      "email",
      "id",
      "name",
      "role",
      "updatedAt",
    ]
  `);
});

// ✅ OK: Serialized data format
test("exports user to JSON", () => {
  const json = exportUserToJSON(user);
  expect(json).toMatchInlineSnapshot(`
    {
      "email": "john@example.com",
      "name": "John Doe",
      "version": "1.0",
    }
  `);
});

Refactoring Process

# Snapshot Refactoring Checklist

For each snapshot test, ask:

1. **What is being tested?**

   - If unclear → Replace with specific assertions

2. **Does it test behavior or implementation?**

   - Implementation → Refactor to behavior test

3. **How often does this change?**

   - Frequently → Use targeted assertions
   - Rarely → Snapshot OK

4. **Can I describe what should pass/fail?**

   - No → Snapshot is too broad

5. **Would a visual test be better?**
   - UI appearance → Use screenshot testing

## Refactoring Steps

1. Run snapshot test, let it fail
2. Look at the diff
3. Extract what actually matters
4. Write assertion for that specific thing
5. Delete snapshot
6. Repeat for next snapshot

Example Refactoring

// ❌ Before: Brittle 200-line snapshot
test("renders dashboard", () => {
  const { container } = render(<Dashboard user={user} />);
  expect(container).toMatchSnapshot();
});

// ✅ After: Multiple focused tests
describe("Dashboard", () => {
  test("displays welcome message with user name", () => {
    render(<Dashboard user={user} />);
    expect(screen.getByText(`Welcome back, ${user.name}!`)).toBeInTheDocument();
  });

  test("shows user stats", () => {
    render(<Dashboard user={user} stats={mockStats} />);

    expect(screen.getByText(`${mockStats.orders} orders`)).toBeInTheDocument();
    expect(screen.getByText(`$${mockStats.revenue}`)).toBeInTheDocument();
  });

  test("displays quick actions", () => {
    render(<Dashboard user={user} />);

    expect(
      screen.getByRole("button", { name: "New Order" })
    ).toBeInTheDocument();
    expect(
      screen.getByRole("button", { name: "View Reports" })
    ).toBeInTheDocument();
  });

  test("shows empty state when no recent activity", () => {
    render(<Dashboard user={user} recentActivity={[]} />);

    expect(screen.getByText("No recent activity")).toBeInTheDocument();
  });
});

Automated Conversion Script

// scripts/convert-snapshots.ts
import * as fs from "fs";
import * as path from "path";

function convertSnapshotToAssertions(testFile: string): string {
  let content = fs.readFileSync(testFile, "utf-8");

  // Replace toMatchSnapshot() with specific assertions
  content = content.replace(
    /expect\((.+?)\)\.toMatchSnapshot\(\)/g,
    (match, element) => {
      return `// TODO: Replace with specific assertions
// expect(${element}).to... `;
    }
  );

  return content;
}

Maintenance Strategy

# Snapshot Maintenance Guidelines

## When to Update Snapshots

✅ **Update when:**

- Intentional design change
- New feature added
- Bug fix that changes output
- Refactoring that changes structure

❌ **Don't update when:**

- "Jest said to update"
- Test is failing
- Don't understand the change
- Too lazy to investigate

## Review Process

1. Run `jest -u` to update
2. Review EVERY changed snapshot
3. Verify change is intentional
4. If unsure, ask for review
5. Consider if assertion would be better

## Reduce Snapshot Size

- Use `.toMatchObject()` for partial matches
- Extract only relevant data
- Use serializers to remove noise
- Consider inline snapshots

Best Practices

  1. Inline snapshots: More visible and reviewable
  2. Small snapshots: Snapshot only what matters
  3. Stable data: Remove timestamps, IDs
  4. Clear intent: Test name explains what's captured
  5. Visual regression: For UI appearance
  6. Regular review: Quarterly snapshot audit
  7. Specific assertions: Prefer over snapshots

Output Checklist

  • Brittle snapshots identified
  • Refactored to specific assertions
  • Inline snapshots where appropriate
  • Unstable data removed (serializers)
  • Partial snapshots for data structures
  • Visual regression for UI
  • Maintenance guidelines documented
  • Review process established

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Audits and implements web accessibility (a11y) following WCAG 2.1 guidelines with ARIA patterns, keyboard navigation, screen reader support, and contrast checking. Use when users request "accessibility audit", "a11y review", "WCAG compliance", "screen reader support", or "keyboard navigation".

日本語の概要は準備中です。原文の説明を表示しています。

sathishssj3/Stereix-Engine22026年10月4日 更新

Creates Architecture Decision Records documenting key technical decisions with context, alternatives considered, tradeoffs, consequences, and decision owners. Use when documenting "architecture decisions", "technical choices", "design decisions", or "ADRs".

日本語の概要は準備中です。原文の説明を表示しています。

sathishssj3/Stereix-Engine22026年10月4日 更新

Designs multi-step agent workflows with tool usage, retry logic, state management, and budget controls. Provides orchestration diagrams, tool execution order, fallback strategies, and cost limits. Use for "AI agents", "agentic workflows", "multi-step AI", or "autonomous systems".

日本語の概要は準備中です。原文の説明を表示しています。

sathishssj3/Stereix-Engine22026年10月4日 更新

MUST USE when user wants to 调研/research/搜索/search/查/找/look up anything on the internet — e.g. 全网调研 X / 帮我调研一下 X / 查一下 X / 搜搜 X / 看看大家怎么评价 X / X 上有什么讨论 / research this topic。 Also MUST USE when user mentions any platform or shares any URL/链接: 小红书/xiaohongshu/xhs, Twitter/推特/X, B站/bilibili, Reddit, Facebook, Instagram, V2EX, LinkedIn/领英/招聘/求职/jobs, YouTube, GitHub code search, 小宇宙播客, 雪球/股票行情, RSS feeds, or any web URL. 15 platforms, multi-backend routing (OpenCLI / per-platform CLIs / APIs). Zero config for 6 channels. Run `agent-reach doctor --json` to see which backend serves each platform right now. NOT for: 写报告/数据分析/翻译等内容加工(本 skill 只负责从互联网获取内容); 发帖/评论/点赞等写操作;已有专门 skill 的平台(先用专门 skill)。 【路由方式】SKILL.md 包含路由表和常用命令,复杂场景需按需阅读对应分类的 references/*.md。 分类:search / social (小红书/推特/B站/V2EX/Reddit/Facebook/Instagram) / career(LinkedIn) / dev(github) / web(网页/文章/RSS) / video(YouTube/B站/播客) / finance(雪球/股票)。

日本語の概要は準備中です。原文の説明を表示しています。

sathishssj3/Stereix-Engine22026年10月4日 更新

Orchestrates multi-agent AI systems with task delegation, agent communication, shared memory, and workflow coordination. Use when users request "multi-agent system", "agent orchestration", "AI agents", "agent coordination", or "autonomous agents".

日本語の概要は準備中です。原文の説明を表示しています。

sathishssj3/Stereix-Engine22026年10月4日 更新

Creates SLO-based alerts and operational dashboards with key charts, alert thresholds, and runbook links. Use for "alerting", "dashboards", "SLO", or "monitoring".

日本語の概要は準備中です。原文の説明を表示しています。

sathishssj3/Stereix-Engine22026年10月4日 更新

sathishssj3 のスキルをすべて見る

このスキルの問題を報告する