Skills Plugins MCP Prompt Model 博客 我的中心
开发编程 #react #browser #writing #ai

front-end-testing

Behavior-driven UI testing patterns across Vitest Browser Mode, Playwright E2E evidence boundaries, and DOM Testing Library. Use when testing any front-end application, writing UI or end-to-end tests, querying DOM elements, simulating user interactions, or choosing the lightest harness that proves a browser-observable claim. For React-specific patterns, see the react-testing skill.

DeepseekModel 官方收录技能 质量 优秀 · 90 v1.0.0

获取

https://deepseekmodel.com/api/download.php?id=citypaul-dotfiles-claude-claude-skills-front-end-testing-skill-md&format=skill
下载 .skill 标准格式,含 system_prompt 与 model_config,导入任意 Agent 框架即可使用
.skill 文件中 system_prompt 字段的实际内容。
name front-end-testing description Behavior-driven UI testing patterns across Vitest Browser Mode, Playwright E2E evidence boundaries, and DOM Testing Library. Use when testing any front-end application, writing UI or end-to-end tests, querying DOM elements, simulating user interactions, or choosing the lightest harness that proves a browser-observable claim. For React-specific patterns, see the react-testing skill. 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-interface testing), load the testing skill. Every hand-back states the harness and where its evidence stops. Whenever you report finished UI test work — the reply, a PR body, a CI step label — name the runner and environment that produced the evidence (Playwright against the served app, Vitest in jsdom, Browser Mode in a real browser) and, in the same breath, the nearest thing it does not prove. A jsdom suite does not prove real rendering, CSS, focus, or the browser's own event dispatch; a component-level suite does not prove the served app, its routing, or the real server; one journey does not prove the paths it never walks. "All tests pass" with the boundary left unsaid reads as a stronger claim than the tests support. Deep-dive resources are in the resources/ directory. Load them on demand: Resource Load when... resources/playwright-e2e.md Writing or auditing Playwright Test E2E/user-journey suites against a running app — who may initiate requests, observing network without performing it, the direct-transport audit, auth/lifecycle evidence resources/async-patterns.md Using findBy / waitFor / waitForElementToBeRemoved , testing loading states, debounce, or reviewing waitFor usage resources/msw.md Mocking APIs — full setupWorker (Browser Mode) and setupServer (Node/jsdom) setup, per-test overrides resources/dom-testing-library-legacy.md Working in a jsdom/ @testing-library/dom codebase — screen object, fireEvent vs userEvent, jest-dom matchers, ESLint plugins Core Philosophy Test behavior users see, not implementation details. This applies in every environment — Browser Mode, jsdom, anything. Your UI has two users: End-users : Interact through the DOM (clicks, typing, reading text) 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." False negatives (tests break on refactor): // ❌ WRONG - Coupled to state implementation; breaks when state → signals → stores it ( 'should update internal state' , () => { const component = new CounterComponent (); component. setState ({ count : 5 }); expect (component. state . count ). toBe ( 5 ); }); False positives (bugs pass tests): // ❌ WRONG - Button exists but onClick is broken; test still passes it ( 'should render button' , () => { render ( '<button data-testid="submit-btn">Submit</button>' ); expect (screen. getByTestId ( 'submit-btn' )). toBeInTheDocument (); }); ✅ CORRECT - Drive the UI the way a user would, assert what the user sees : type into labelled fields, click the submit button, assert the submit handler received the form data. This survives refactors, tests the contract, and catches real bugs (broken onClick, validation errors). Vitest Browser Mode for Browser-Observable Behaviour Prefer Vitest Browser Mode when the claim depends on real rendering, CSS, events, focus management, accessibility, or browser APIs and the repository already supports it or the added harness cost is justified. Keep an existing stable jsdom/happy-dom harness, or use a lighter environment, when it proves pure logic or component contracts without browser-specific behaviour. Why Browser Mode Over jsdom Aspect jsdom/happy-dom Browser Mode Environment Simulated DOM in Node.js Real browser (Chromium/Firefox/WebKit) CSS Not rendered Real CSS rendering, layout, computed styles Events Synthetic JS events CDP-based real browser events APIs Subset of Web APIs Full browser API surface Focus/a11y Approximate Real focus management, accessibility tree Debugging Console only Full browser DevTools Setup Inspect the repository's package manager, lockfile, existing test harness, and installed versions before changing dependencies or configuration. If a new harness is justified and the user has authorized setup, select exact mutually compatible versions from the official compatibility/peer-dependency evidence, install them with the repository package manager, and invoke only the repository-local binaries (no implicit download). For example: <repo-pm> add --save-dev vitest@<reviewed-version> @vitest/browser-playwright@<reviewed-version> <repo-pm> exec playwright install chromium # inspect this binary download before authorizing it // 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' }], }, }, }) If the reviewed installed version provides it, run the local setup wizard with <repo-pm> exec vitest init browser ; inspect its planned config writes first. Focused Browser-Test Feedback Apply the tdd skill's fast-feedback policy to browser tests too: Vitest Browser Mode follows the same repository-owned versus diff-selected strategy, lifecycle, cleanup, native-discovery, and live-proof rules in the tdd skill and its Vitest watch reference . The Node/SSR 4.1.10 clean-start proof does not prove Browser Mode; verify its installed version/configuration independently. Do not assume --changed --watch reloads VCS impact after startup. Browser dependencies are often outside the import graph. Widen for routing, global styling, browser setup, templates, generated assets, type-only relationships, browser-mode orchestration, and Docker-backed services. Preserve repository watchTriggerPatterns , forceRerunTriggers , and root monorepo project/task graphs. Playwright Test has a native affected one-shot: prefer the repository script or playwright test --only-changed[=<real-base>] for GREEN/REFACTOR when the installed version supports it. It selects changed test files and tests that import changed files, but Playwright documents this as a heuristic. Browser journeys often exercise application code at runtime rather than importing it, and dynamic/non-import dependencies can remain invisible. For those changes, use the repository-mapped affected journey/project set, including every consumer of shared fixtures, auth state, setup, routing, styling, and UI packages; widen when uncertain. Use a Playwright file, --grep , --last-failed , or hand-picked project filter only to prove RED or debug a known failure. For GREEN/REFACTOR, project filters are valid only when the runner/workspace graph mechanically derived the complete affected project set, including transitive consumers. Confirm --only-changed actually executes expected tests; an empty selection is not GREEN evidence. With a one-shot runner, rerun the affected command after creating a test. Never count an empty affected set, Vitest --passWithNoTests , or Playwright --pass-with-no-tests as evidence. At PR readiness, stop watchers and apply the target repository's mutation policy plus complete non-watch test gate. That gate includes the full required UI matrix across every configured browser/project; targeted Chromium-only, --grep , or UI-only evidence is insufficient. 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' ) In jsdom codebases, use @testing-library/user-event instead — prefer it over fireEvent for user interactions (see resources/dom-testing-library-legacy.md ). Create a fresh userEvent.setup() per test by default. An isolated beforeEach is also valid when it creates a new instance for each non-concurrent test; never reuse one suite-global user instance. 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. vi.mock('./module', { spy: true }) works, but treat module mocking as temporary scaffolding — prefer parameter injection so the dependency is an explicit seam (load the finding-seams skill). It is never the answer for a module that makes network requests: mock that at the network with MSW, in every environment and on error paths as well as happy paths. alert() / confirm() : Thread-blocking dialogs halt browser execution. Mock them with vi.spyOn(window, 'alert').mockImplementation(() => {}) . act() : Not needed for component interactions via locators — CDP events + expect.element() retry handle timing. renderHook state updates still need act (see react-testing ). 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 identifiers with enough entropy for parallel runs (for example, crypto.randomUUID() ); timestamps alone can collide 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- ${crypto.randomUUID()} ` try { await page. getByLabelText ( /name/i ). fill (uniqueName) await page. getByRole ( 'button' , { name : /create/i }). click () await expect. element (page. getByText (uniqueName)). toBeVisible () } finally { await testData. deleteUserByName (uniqueName) // repository-owned idempotent cleanup fixture } }) 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. Playwright E2E Is a Different Subject Vitest Browser Mode tests a component in isolation ; Playwright Test against a running application tests whatever the test's claim names — a user journey, the frontend's own network behavior, cookie/CSRF posture, redirects, rendering. Same browser engines, different subject and harness: never assume guidance transfers between them. One claim, one harness. Prove a claim with the lightest harness that can fail when the claim is false, and stop there. Behaviour inside one mounted component — a bug fix, an error path, a disabled button that must recover — is proved by the component-level harness; adding an E2E spec that re-walks it buys no evidence, only a second suite to maintain and a slower gate. Reach for Playwright when the claim itself is the served application: navigation, several screens in sequence, the real server, cookies, redirects. If you have already written the component test, adding the journey needs a reason you can state. The one rule that governs E2E suites: a browser or user-journey claim must be proved by a browser initiator — an accessible locator action or a navigation — never by a direct HTTP call standing in for the user or the frontend. page.request.post('/api/...') in a test named "user creates ..." proves an HTTP contract, not a journey; it stays green when the button, cookie policy, CSRF check, redirect, or rendering breaks. Load resources/playwright-e2e.md before writing or reviewing any E2E/journey suite — it carries the decision rule, the evidence-boundary table, safe request observation, the direct-transport audit procedure, and the auth/lifecycle evidence contract. Query Selection Priority Most critical skill: choosing the right query. Near-identical for Browser Mode locators and Testing Library queries — the two naming differences are flagged below. Use queries in this order (accessibility-first): getByRole - Highest priority. Queries by ARIA role + accessible name; mirrors screen reader experience; forces semantic HTML getByLabelText - Form fields, via associated <label> getByPlaceholder - Fallback for inputs when no label (placeholder shouldn't replace a label). Testing Library's name is getByPlaceholderText getByText - Non-interactive content users read getByDisplayValue - Inputs with pre-filled values. Testing Library only — Browser Mode has no such locator; use getByRole + a value assertion instead getByAltText - Images getByTitle - Rare, when other queries unavailable getByTestId - Last resort only; not user-facing Query Variants (Testing Library) getBy* - Element must exist (throws if not found). Use when asserting existence. queryBy* - Returns null if not found. Use when asserting non-existence . findBy* - Async, waits for element to appear. See resources/async-patterns.md . (Browser Mode locators are lazy and retried by expect.element() , so the get/query/find split mostly disappears — use .not.toBeInTheDocument() via expect.element for absence.) Common Mistakes // ❌ WRONG - querySelector (DOM implementation detail) const button = container. querySelector ( '.submit-button' ); // ❌ WRONG - testId when a role is available (not how users find the button) screen. getByTestId ( 'submit-button' ); // ❌ WRONG - role without accessible name (which button? pages have many) screen. getByRole ( 'button' ); // ✅ CORRECT - role + accessible name (how screen readers find it) screen. getByRole ( 'button' , { name : /submit/i }); // ❌ WRONG - getBy to assert non-existence (awkward throw-based check)
Agent 识别该技能的关键词,点击任意一个即可复制。

该技能未提供触发词。

下载的 .skill 包内含以下字段。
字段 说明
format格式标识(skill/v1)
skill_id技能唯一 ID
name技能名称
version版本号
description技能描述
category所属分类(数组)
trigger_words触发词列表
tags标签列表
source来源标识
source_url来源链接(本页地址)
exported_at导出时间(每次下载生成)
system_prompt系统提示词正文
model_config模型参数:provider / model / temperature / max_tokens / top_p
examples示例
install_guide各平台导入说明(Coze / Dify / Claude / 自定义框架)
同一份技能可按不同平台格式导出。
.skill 标准格式,含 system_prompt 与 model_config,导入任意 Agent 框架即可使用 下载
.skillpro 增强格式,额外含脚本 / 工具 / 依赖 / 钩子占位 下载
.json 纯 JSON 导出,只含 system_prompt 与模型参数 下载
Coze 带 frontmatter 的 Markdown,Coze 平台导入用 下载
Dify Dify DSL,创建应用后直接导入 下载

每日精选 Skill 推荐,免费送到你邮箱

输入邮箱,每天接收一个精选 AI Agent 技能推荐。完全免费,持续更新。

提交后我们会发送一封确认邮件,点击邮件里的链接才会开始收信。

完全免费,取消任意时间。我们不会发送垃圾邮件。