Token导航 LogoToken导航

Agent Skill · 研究检索

front-end-testing(前端测试)

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

front-end-testing 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为操作浏览器;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 72,323。

总安装 188周安装 8GitHub Stars 633下载 66核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:front-end-testing(前端测试)
来源仓库:https://github.com/citypaul/dotfiles
仓库路径:skills/front-end-testing
安装命令:
npx skills add https://github.com/citypaul/dotfiles --skill front-end-testing
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/citypaul/dotfiles --skill front-end-testing

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

front-end-testing 用于辅助测试设计、自动化测试、用例整理和回归验证。适合编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑。涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

暂无额外注意事项,建议参考来源仓库获取最新使用说明。

来源仓库内路径:skills/front-end-testing

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/citypaul/dotfiles --skill front-end-testing;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要操作浏览器,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

front-end-testing 怎么安装?

在终端执行 npx skills add https://github.com/citypaul/dotfiles --skill front-end-testing。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

front-end-testing 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

front-end-testing 需要什么权限?

权限级别是操作浏览器。该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

front-end-testing 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

front-end-testing 用的人多吗?

公开数据是累计安装 188 次,近一周安装 8 次,下载 66 次,GitHub 633 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

front-end-testing 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
front-end-testing

前端测试 · 本页

188633操作浏览器未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Front-End Testing

For React-specific patterns (components, hooks, context), load the react-testing skill. For TDD workflow, load the tdd skill. For general testing patterns (factories, public API testing), load the testing skill.

Vitest Browser Mode (Preferred)

Always prefer Vitest Browser Mode over jsdom/happy-dom. Tests run in a real browser (via Playwright), giving production-accurate behavior for CSS, events, focus management, and accessibility.

Why Browser Mode Over jsdom

Aspectjsdom/happy-domBrowser Mode
EnvironmentSimulated DOM in Node.jsReal browser (Chromium/Firefox/WebKit)
CSSNot renderedReal CSS rendering, layout, computed styles
EventsSynthetic JS eventsCDP-based real browser events
APIsSubset of Web APIsFull browser API surface
Focus/a11yApproximateReal focus management, accessibility tree
DebuggingConsole onlyFull browser DevTools

Setup

npm install -D vitest @vitest/browser-playwright
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import { playwright } from '@vitest/browser-playwright'

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: playwright(),
      headless: true,
      instances: [{ browser: 'chromium' }],
    },
  },
})

Quick setup wizard: npx vitest init browser

Built-in Locators

Vitest Browser Mode has built-in locators that mirror Testing Library queries. No separate @testing-library/dom import needed.

import { page } from 'vitest/browser'

// These work exactly like Testing Library queries
page.getByRole('button', { name: /submit/i })
page.getByText(/welcome/i)
page.getByLabelText(/email/i)
page.getByPlaceholder(/search/i)
page.getByAltText(/logo/i)
page.getByTestId('my-element')  // Last resort only

Built-in Assertions with Retry

Use expect.element() for DOM assertions — it automatically retries until the assertion passes or times out, reducing flakiness:

// ✅ CORRECT - Auto-retrying assertion
await expect.element(page.getByText(/success/i)).toBeVisible()
await expect.element(page.getByRole('button')).toBeDisabled()

// Available matchers (no @testing-library/jest-dom needed):
await expect.element(el).toBeVisible()
await expect.element(el).toBeDisabled()
await expect.element(el).toHaveTextContent(/text/i)
await expect.element(el).toHaveValue('input value')
await expect.element(el).toHaveAttribute('aria-label', 'Close')
await expect.element(el).toBeChecked()

Built-in User Events (CDP-based)

import { userEvent } from 'vitest/browser'

// Real browser events via Chrome DevTools Protocol
await userEvent.click(page.getByRole('button', { name: /submit/i }))
await userEvent.fill(page.getByLabelText(/email/i), 'test@example.com')
await userEvent.keyboard('{Enter}')
await userEvent.selectOptions(page.getByLabelText(/country/i), 'USA')
await userEvent.clear(page.getByLabelText(/search/i))

Or use locator methods directly:

await page.getByRole('button', { name: /submit/i }).click()
await page.getByLabelText(/email/i).fill('test@example.com')

Multi-Project Setup (Node + Browser)

When you need both unit tests (Node) and UI tests (browser):

export default defineConfig({
  test: {
    projects: [
      {
        test: {
          include: ['tests/unit/**/*.test.ts'],
          name: 'unit',
          environment: 'node',
        },
      },
      {
        test: {
          include: ['tests/browser/**/*.test.ts'],
          name: 'browser',
          browser: {
            enabled: true,
            provider: playwright(),
            instances: [{ browser: 'chromium' }],
          },
        },
      },
    ],
  },
})

Browser Mode Gotchas

  • vi.spyOn on imports: ES module namespaces are sealed in real browsers. Use vi.mock('./module', {spy: true}) instead.
  • alert()/confirm(): Thread-blocking dialogs halt browser execution. Mock them with vi.spyOn(window, 'alert').mockImplementation(() => {}).
  • act() not needed: CDP events + expect.element() retry handle timing automatically.

Playwright / Browser Mode Test Idempotency

All Playwright-style tests MUST be idempotent. Every test must produce the same result regardless of execution order, how many times it runs, or what other tests ran before it.

Rules:

  • Each test creates its own state from scratch — never depend on another test's side effects
  • Clean up any persistent state (database rows, localStorage, cookies) created during the test
  • Use unique identifiers (e.g., timestamp-based) to avoid collisions when tests run in parallel
  • Never assume the DOM is in a particular state at the start of a test — render fresh
  • If tests share a server or database, use isolation strategies (transactions, test-specific data)
// ❌ WRONG - Tests depend on shared state
it('creates a user', async () => {
  await page.getByRole('button', { name: /create/i }).click()
  // Creates user "Alice" in the database
})

it('lists users', async () => {
  // Assumes "Alice" exists from previous test!
  await expect.element(page.getByText('Alice')).toBeVisible()
})

// ✅ CORRECT - Each test is self-contained
it('creates and displays a user', async () => {
  const uniqueName = `User-${Date.now()}`
  await page.getByLabelText(/name/i).fill(uniqueName)
  await page.getByRole('button', { name: /create/i }).click()
  await expect.element(page.getByText(uniqueName)).toBeVisible()
})

Why this matters: Browser Mode can run tests in parallel across multiple browser instances. Non-idempotent tests will produce flaky failures that are nearly impossible to debug.


Legacy: DOM Testing Library Patterns

The patterns below apply when using @testing-library/dom directly (e.g., with jsdom). Prefer Vitest Browser Mode for new projects — the query patterns are identical but built-in.


Core Philosophy

Test behavior users see, not implementation details.

Testing Library exists to solve a fundamental problem: tests that break when you refactor (false negatives) and tests that pass when bugs exist (false positives).

Two Types of Users

Your UI components have two users:

  1. End-users: Interact through the DOM (clicks, typing, reading text)
  2. Developers: You, refactoring implementation

Kent C. Dodds principle: "The more your tests resemble the way your software is used, the more confidence they can give you."

Why This Matters

False negatives (tests break on refactor):

// ❌ WRONG - Testing implementation (will break on refactor)
it('should update internal state', () => {
  const component = new CounterComponent();
  component.setState({ count: 5 }); // Coupled to state implementation
  expect(component.state.count).toBe(5);
});

False positives (bugs pass tests):

// ❌ WRONG - Testing wrong thing
it('should render button', () => {
  render('<button data-testid="submit-btn">Submit</button>');
  expect(screen.getByTestId('submit-btn')).toBeInTheDocument();
  // Button exists but onClick is broken - test passes!
});

Correct approach (behavior-driven):

// ✅ CORRECT - Testing user-visible behavior
it('should submit form when user clicks submit', async () => {
  const handleSubmit = vi.fn();
  const user = userEvent.setup();

  render(`
    <form id="login-form">
      <label>Email: <input name="email" /></label>
      <label>Password: <input name="password" type="password" /></label>
      <button type="submit">Submit</button>
    </form>
  `);

  document.getElementById('login-form').addEventListener('submit', (e) => {
    e.preventDefault();
    handleSubmit(new FormData(e.target));
  });

  await user.type(screen.getByLabelText(/email/i), 'test@example.com');
  await user.type(screen.getByLabelText(/password/i), 'password123');
  await user.click(screen.getByRole('button', { name: /submit/i }));

  expect(handleSubmit).toHaveBeenCalled();
});

This test:

  • Survives refactoring (state → signals → stores)
  • Tests the contract (what users see)
  • Catches real bugs (broken onClick, validation errors)

Query Selection Priority

Most critical Testing Library skill: choosing the right query.

Priority Order

Use queries in this order (accessibility-first):

  1. getByRole - Highest priority

- Queries by ARIA role + accessible name - Mirrors screen reader experience - Forces semantic HTML

  1. getByLabelText - Form fields

- Finds inputs by associated <label> - Ensures accessible forms

  1. getByPlaceholderText - Fallback for inputs

- Only when label not present - Placeholder shouldn't replace label

  1. getByText - Non-interactive content

- Headings, paragraphs, list items - Content users read

  1. getByDisplayValue - Current form values

- Inputs with pre-filled values

  1. getByAltText - Images

- Ensures accessible images

  1. getByTitle - SVG titles, title attributes

- Rare, when other queries unavailable

  1. getByTestId - Last resort only

- When no other query works - Not user-facing

Query Variants

Three variants for every query:

**getBy*** - Element must exist (throws if not found)

// ✅ Use when asserting element EXISTS
const button = screen.getByRole('button', { name: /submit/i });
expect(button).toBeDisabled();

**queryBy*** - Returns null if not found

// ✅ Use when asserting element DOESN'T exist
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();

// ❌ WRONG - getBy throws, can't assert non-existence
expect(() => screen.getByRole('dialog')).toThrow(); // Ugly!

**findBy*** - Async, waits for element to appear

// ✅ Use when element appears after async operation
const message = await screen.findByText(/success/i);

Common Mistakes

❌ Using container.querySelector

const button = container.querySelector('.submit-button'); // DOM implementation detail

✅ CORRECT - Query by accessible role

const button = screen.getByRole('button', { name: /submit/i }); // User-facing

❌ Using getByTestId when role available

screen.getByTestId('submit-button'); // Not how users find button

✅ CORRECT - Query by role

screen.getByRole('button', { name: /submit/i }); // How screen readers find it

❌ Not using accessible names

screen.getByRole('button'); // Which button? Multiple on page!

✅ CORRECT - Specify accessible name

screen.getByRole('button', { name: /submit/i }); // Specific button

❌ Using getBy to assert non-existence

expect(() => screen.getByText(/error/i)).toThrow(); // Awkward

✅ CORRECT - Use queryBy

expect(screen.queryByText(/error/i)).not.toBeInTheDocument();

User Event Simulation

Always use userEvent over fireEvent for realistic interactions.

userEvent vs fireEvent

Why userEvent is superior:

  • Simulates complete interaction sequence (hover → focus → click → blur)
  • Triggers all associated events
  • Respects browser timing and order
  • Catches more bugs
// ❌ WRONG - fireEvent (incomplete simulation)
fireEvent.change(input, { target: { value: 'test' } });
fireEvent.click(button);
// ✅ CORRECT - userEvent (realistic simulation)
const user = userEvent.setup();
await user.type(input, 'test');
await user.click(button);

Only use fireEvent when:

  • userEvent doesn't support the event (rare)
  • Testing non-standard browser behavior

userEvent.setup() Pattern

Modern best practice (2025):

// ✅ CORRECT - Setup per test
it('should handle user input', async () => {
  const user = userEvent.setup(); // Fresh instance per test
  render('<input aria-label="Email" />');

  await user.type(screen.getByLabelText(/email/i), 'test@example.com');
});
// ❌ WRONG - Setup in beforeEach
let user;
beforeEach(() => {
  user = userEvent.setup(); // Shared state across tests
});

it('test 1', async () => {
  await user.click(...); // Might affect test 2
});

Why: Each test gets clean state, prevents test interdependence.

Common Interactions

Clicking:

const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: /submit/i }));

Typing:

await user.type(screen.getByLabelText(/email/i), 'test@example.com');

Keyboard:

await user.keyboard('{Enter}'); // Press Enter
await user.keyboard('{Shift>}A{/Shift}'); // Shift+A

Selecting options:

await user.selectOptions(
  screen.getByLabelText(/country/i),
  'USA'
);

Clearing input:

await user.clear(screen.getByLabelText(/search/i));

Async Testing Patterns

UI frameworks are async by nature (state updates, API calls, suspense). Testing Library provides utilities for async scenarios.

findBy Queries

Built-in async queries (combines getBy + waitFor):

// ✅ CORRECT - Wait for element to appear
const message = await screen.findByText(/success/i);

// Under the hood: retries getByText until it succeeds or timeout

When to use:

  • Element appears after async operation
  • Loading states disappear
  • API responses render content

Configuration:

// Default: 1000ms timeout
const message = await screen.findByText(/success/i);

// Custom timeout
const message = await screen.findByText(/success/i, {}, { timeout: 3000 });

waitFor Utility

For complex conditions that findBy can't handle:

// ✅ CORRECT - Complex assertion
await waitFor(() => {
  expect(screen.getByText(/loaded/i)).toBeInTheDocument();
});

// ✅ CORRECT - Multiple elements
await waitFor(() => {
  expect(screen.getAllByRole('listitem')).toHaveLength(10);
});

waitFor retries until:

  • Assertion passes (doesn't throw)
  • Timeout reached (default 1000ms)

Common mistakes:

❌ Side effects in waitFor

await waitFor(() => {
  fireEvent.click(button); // Side effect! Will click multiple times
  expect(result).toBe(true);
});

✅ CORRECT - Only assertions

fireEvent.click(button); // Outside waitFor
await waitFor(() => {
  expect(result).toBe(true); // Only assertion
});

❌ Multiple assertions

await waitFor(() => {
  expect(screen.getByText(/name/i)).toBeInTheDocument();
  expect(screen.getByText(/email/i)).toBeInTheDocument(); // Might not retry both
});

✅ CORRECT - Single assertion per waitFor

await waitFor(() => {
  expect(screen.getByText(/name/i)).toBeInTheDocument();
});
expect(screen.getByText(/email/i)).toBeInTheDocument();

❌ Wrapping findBy in waitFor

await waitFor(() => screen.findByText(/success/i)); // Redundant!

✅ CORRECT - findBy already waits

await screen.findByText(/success/i);

waitForElementToBeRemoved

For disappearance scenarios:

// ✅ CORRECT - Wait for loading spinner to disappear
await waitForElementToBeRemoved(() => screen.queryByText(/loading/i));

// ✅ CORRECT - Wait for modal to close
await waitForElementToBeRemoved(() => screen.queryByRole('dialog'));

Note: Must use queryBy* (returns null) not getBy* (throws).

Common Patterns

Loading states:

render('<div id="container"></div>');

// Simulate async data loading
const container = document.getElementById('container');
container.innerHTML = '<p>Loading...</p>';

// Initially loading
expect(screen.getByText(/loading/i)).toBeInTheDocument();

// Simulate data load
setTimeout(() => {
  container.innerHTML = '<p>John Doe</p>';
}, 100);

// Wait for data
await screen.findByText(/john doe/i);

// Loading gone
expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();

API responses:

const user = userEvent.setup();
render(`
  <form>
    <label>Search: <input name="search" /></label>
    <button type="submit">Search</button>
    <ul id="results"></ul>
  </form>
`);

await user.type(screen.getByLabelText(/search/i), 'react');
await user.click(screen.getByRole('button', { name: /search/i }));

// Wait for results (after API response)
await waitFor(() => {
  expect(screen.getAllByRole('listitem')).toHaveLength(10);
});

Debounced inputs:

const user = userEvent.setup();
render(`
  <label>Search: <input id="search" /></label>
  <ul id="suggestions"></ul>
`);

await user.type(screen.getByLabelText(/search/i), 'react');

// Wait for debounced suggestions
await screen.findByText(/react testing library/i);

MSW Integration

Mock Service Worker for API-level mocking.

Why MSW

Network-level interception:

  • Intercepts requests at network layer (not fetch/axios mocks)
  • Same mocks work in tests, Storybook, development
  • No client-specific mocking logic
  • Tests real request logic
// ❌ WRONG - Mocking fetch implementation
vi.spyOn(global, 'fetch').mockResolvedValue({
  json: async () => ({ users: [...] }),
}); // Tight coupling, won't work in Storybook
// ✅ CORRECT - MSW intercepts at network level
// Works in tests, Storybook, dev server
http.get('/api/users', () => {
  return HttpResponse.json({ users: [...] });
});

setupServer Pattern

In test setup file:

// test-setup.ts
import { setupServer } from 'msw/node';
import { handlers } from './mocks/handlers';

export const server = setupServer(...handlers);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

In handlers file:

// mocks/handlers.ts
import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('/api/users', () => {
    return HttpResponse.json({
      users: [
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' },
      ],
    });
  }),
];

Per-Test Overrides

Override handlers for specific tests:

it('should handle API error', async () => {
  // Override for this test only
  server.use(
    http.get('/api/users', () => {
      return HttpResponse.json(
        { error: 'Server error' },
        { status: 500 }
      );
    })
  );

  render('<div id="user-list"></div>');

  // Simulate component fetching users
  fetch('/api/users').then(() => {
    document.getElementById('user-list').innerHTML =
      '<p>Failed to load users</p>';
  });

  await screen.findByText(/failed to load users/i);
});

After test, afterEach resets to default handlers.


Accessibility-First Testing

Why Accessible Queries

Three benefits:

  1. Tests mirror real usage - Query like screen readers do
  2. Improves app accessibility - Tests force accessible markup
  3. Refactor-friendly - Coupled to user experience, not implementation
// ❌ WRONG - Implementation detail
screen.getByTestId('user-menu');

// ✅ CORRECT - Accessibility query
screen.getByRole('button', { name: /user menu/i });

If accessible query fails, your app has an accessibility issue.

ARIA Attributes

When to add ARIA:

✅ Custom components (where semantic HTML unavailable):

<div role="dialog" aria-label="Confirmation Dialog">
  <h2>Are you sure?</h2>
  ...
</div>

Query:

screen.getByRole('dialog', { name: /confirmation/i });

❌ DON'T add to semantic HTML (redundant):

<!-- ❌ WRONG - Semantic HTML already has role -->
<button role="button">Submit</button>

<!-- ✅ CORRECT - Semantic HTML is enough -->
<button>Submit</button>

Semantic HTML Priority

Always prefer semantic HTML over ARIA:

<!-- ❌ WRONG - Custom element + ARIA -->
<div role="button" onclick="handleClick()" tabindex="0">
  Submit
</div>

<!-- ✅ CORRECT - Semantic HTML -->
<button onclick="handleClick()">
  Submit
</button>

Semantic HTML provides:

  • Built-in keyboard navigation
  • Built-in focus management
  • Built-in screen reader support
  • Less code, more accessibility

Testing Library Anti-Patterns

1. Not using screen object

❌ WRONG - Query from render result

const { getByRole } = render('<button>Submit</button>');
const button = getByRole('button');

✅ CORRECT - Use screen

render('<button>Submit</button>');
const button = screen.getByRole('button');

Why: screen is consistent, no destructuring, better error messages.


2. Using querySelector

❌ WRONG - DOM implementation

const { container } = render('<button class="submit-btn">Submit</button>');
const button = container.querySelector('.submit-btn');

✅ CORRECT - Accessible query

render('<button>Submit</button>');
const button = screen.getByRole('button', { name: /submit/i });

3. Testing implementation details

❌ WRONG - Internal state

const component = new Component();
expect(component._internalState).toBe('value'); // Private implementation

✅ CORRECT - User-visible behavior

render('<div id="output"></div>');
expect(screen.getByText(/value/i)).toBeInTheDocument();

4. Not using jest-dom matchers

❌ WRONG - Manual assertions

expect(button.disabled).toBe(true);
expect(element.classList.contains('active')).toBe(true);

✅ CORRECT - jest-dom matchers

expect(button).toBeDisabled();
expect(element).toHaveClass('active');

Install: npm install -D @testing-library/jest-dom


5. Manual cleanup() calls

❌ WRONG - Manual cleanup

afterEach(() => {
  cleanup(); // Automatic in modern Testing Library!
});

✅ CORRECT - No cleanup needed

// Cleanup happens automatically

6. Wrong assertion methods

❌ WRONG - Property access

expect(input.value).toBe('test');
expect(checkbox.checked).toBe(true);

✅ CORRECT - jest-dom matchers

expect(input).toHaveValue('test');
expect(checkbox).toBeChecked();

7. beforeEach render pattern

❌ WRONG - Shared render in beforeEach

let button;
beforeEach(() => {
  render('<button>Submit</button>');
  button = screen.getByRole('button'); // Shared state
});

it('test 1', () => {
  // Uses shared button from beforeEach
});

✅ CORRECT - Factory function per test

const renderButton = () => {
  render('<button>Submit</button>');
  return {
    button: screen.getByRole('button'),
  };
};

it('test 1', () => {
  const { button } = renderButton(); // Fresh state
});

For factory patterns, see testing skill.


8. Multiple assertions in waitFor

❌ WRONG - Multiple assertions

await waitFor(() => {
  expect(screen.getByText(/name/i)).toBeInTheDocument();
  expect(screen.getByText(/email/i)).toBeInTheDocument();
});

✅ CORRECT - Single assertion per waitFor

await waitFor(() => {
  expect(screen.getByText(/name/i)).toBeInTheDocument();
});
expect(screen.getByText(/email/i)).toBeInTheDocument();

9. Side effects in waitFor

❌ WRONG - Mutation in callback

await waitFor(() => {
  fireEvent.click(button); // Clicks multiple times!
  expect(result).toBe(true);
});

✅ CORRECT - Side effects outside

fireEvent.click(button);
await waitFor(() => {
  expect(result).toBe(true);
});

10. Exact string matching

❌ WRONG - Fragile exact match

screen.getByText('Welcome, John Doe'); // Breaks on whitespace change

✅ CORRECT - Regex for flexibility

screen.getByText(/welcome.*john doe/i);

11. Wrong query variant for assertion

❌ WRONG - getBy for non-existence

expect(() => screen.getByText(/error/i)).toThrow();

✅ CORRECT - queryBy

expect(screen.queryByText(/error/i)).not.toBeInTheDocument();

12. Wrapping findBy in waitFor

❌ WRONG - Redundant

await waitFor(() => screen.findByText(/success/i));

✅ CORRECT - findBy already waits

await screen.findByText(/success/i);

13. Using testId when role available

❌ WRONG - testId

screen.getByTestId('submit-button');

✅ CORRECT - Role

screen.getByRole('button', { name: /submit/i });

14. Not installing ESLint plugins

Install these plugins:

npm install -D eslint-plugin-testing-library eslint-plugin-jest-dom

.eslintrc.js:

{
  extends: [
    'plugin:testing-library/dom', // For framework-agnostic
    // OR 'plugin:testing-library/react' for React
    'plugin:jest-dom/recommended',
  ],
}

Catches anti-patterns automatically.


Summary Checklist

Before merging UI tests, verify:

  • Preferred: Using Vitest Browser Mode with real browser (not jsdom/happy-dom)
  • All Playwright/Browser Mode tests are idempotent (no shared state between tests)
  • Using getByRole as first choice for queries (built-in or Testing Library)
  • Using expect.element() for auto-retrying assertions (Browser Mode)
  • Using userEvent for interactions (CDP-based in Browser Mode, or @testing-library/user-event)
  • Testing behavior users see, not implementation details
  • No manual cleanup() calls (automatic)
  • No manual act() calls (Browser Mode handles timing)
  • MSW for API mocking (not fetch/axios mocks)
  • Following TDD workflow (see tdd skill)
  • Using test factories for data (see testing skill)
  • For React-specific patterns (hooks, context, components), see react-testing skill

平台分布

Codex

37.63%
按下载量换算25

Claude

29.97%
按下载量换算20

Cursor

20.23%
按下载量换算13

Gemini CLI

9.38%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills