Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

test(web): tighten browser test admission and trim low-value coverage (#42373)

yyh9e7856f22bfd
diff --git a/.agents/skills/frontend-code-review/references/testing.md b/.agents/skills/frontend-code-review/references/testing.md
index 93b349b21bb..3a8b4656ecc 100644
--- a/.agents/skills/frontend-code-review/references/testing.md
+++ b/.agents/skills/frontend-code-review/references/testing.md
@@ -13,7 +13,7 @@ Flag missing coverage when a change alters a reachable contract such as:
- Accessibility-critical labels, keyboard flow, focus, disabled state, or overlay behavior.
- A regression-prone business rule or bug fix that can be reproduced through a public boundary.
-Do not request tests for mechanical changes, pass-through wrappers, implementation details, or visual-only styling unless they affect behavior. Low coverage alone is not a finding.
+Do not request tests for mechanical changes, pass-through wrappers, implementation details, or incidental visual styling. Low coverage alone is not a finding.
## Flag Low-Value or Fragile Tests
@@ -31,6 +31,7 @@ Flag tests that:
- Prefer semantic queries and accessible names.
- Prefer real feature components when integration semantics matter.
- Check mocks against the owning package's policy; allowed mocks must preserve the public contract and leave the behavior under review real.
-- Require a real-browser or visual verification plan when `happy-dom` cannot represent the risk.
+- Apply the owning package's admission policy before requesting new automation. Real-browser verification can be a one-off review; a simulator limitation alone does not justify a permanent test.
+- Check that assertions prove the claimed outcome and add evidence beyond existing tests; a browser runtime does not make weak assertions stronger.
Treat test quality, determinism, and regression value as the review criteria. Do not use test count or coverage percentage as a proxy for quality.
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index bbd9b7170bb..d59c4fc58ca 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -19,6 +19,6 @@
- [ ] This change requires a documentation update, included: [Dify Document](https://github.com/langgenius/dify-docs)
- [ ] I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
-- [ ] I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
+- [ ] I've verified the change and added or updated tests where meaningful regression risk justifies coverage.
- [ ] I've updated the documentation accordingly.
- [ ] I ran `make lint && make type-check` (backend) and `vp staged` (frontend) to appease the lint gods
diff --git a/packages/dify-ui/docs/testing.md b/packages/dify-ui/docs/testing.md
index 90cc1c11680..effc958730a 100644
--- a/packages/dify-ui/docs/testing.md
+++ b/packages/dify-ui/docs/testing.md
@@ -12,6 +12,8 @@ diagnostics. Run the remaining commands from `packages/dify-ui/`:
This guide owns the Dify UI testing policy and runtime setup. Add tests for observable Dify
integration behavior or a reproducible regression, not merely because a component or prop exists.
+Check existing stories and tests before adding coverage. Browser execution alone does not justify
+a new case; review incidental visual adjustments in Storybook without adding a permanent test.
The package has two [Vitest projects]. Both run in Playwright Chromium [Browser Mode]; the project
name identifies the behavior owner, not a different runtime.
diff --git a/web/app/components/main-nav/__tests__/card-grid.browser.spec.tsx b/web/app/components/main-nav/__tests__/card-grid.browser.spec.tsx
deleted file mode 100644
index d3e11dcb32f..00000000000
--- a/web/app/components/main-nav/__tests__/card-grid.browser.spec.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import { cn } from '@langgenius/dify-ui/cn'
-import { render } from 'vitest-browser-react'
-import { APP_LIST_GRID_CLASS_NAME } from '@/app/components/apps/constants'
-import { MAIN_NAV_APP_CARD_GRID_CLASS_NAME } from '../app-card-grid'
-
-const cardIds = ['first', 'second', 'third', 'fourth']
-
-function CardGrid({
- className,
- label,
- width,
-}: {
- className: string
- label: string
- width: number
-}) {
- return (
- <section aria-label={label} className={className} style={{ width }}>
- {cardIds.map((id) => (
- <article key={id} aria-label={id} className="h-10" />
- ))}
- </section>
- )
-}
-
-describe('Main navigation card grid', () => {
- it('aligns Studio starred and app cards and remains overflow-free in a narrow container', async () => {
- // happy-dom does not resolve CSS Grid tracks or browser layout geometry.
- const screen = await render(
- <>
- <CardGrid label="Starred apps" className={APP_LIST_GRID_CLASS_NAME} width={1264} />
- <CardGrid label="All apps" className={APP_LIST_GRID_CLASS_NAME} width={1264} />
- <CardGrid
- label="Narrow card grid"
- className={cn('gap-2.5', MAIN_NAV_APP_CARD_GRID_CLASS_NAME)}
- width={280}
- />
- </>,
- )
-
- const starredGrid = screen.getByRole('region', { name: 'Starred apps' })
- const starredGridRect = starredGrid.element().getBoundingClientRect()
- const starredCardRects = starredGrid
- .getByRole('article')
- .elements()
- .map((element) => element.getBoundingClientRect())
- const appCardRects = screen
- .getByRole('region', { name: 'All apps' })
- .getByRole('article')
- .elements()
- .map((element) => element.getBoundingClientRect())
-
- expect(new Set(starredCardRects.map((rect) => rect.top)).size).toBe(1)
- expect(starredCardRects[0]!.left - starredGridRect.left).toBeCloseTo(32)
- expect(starredCardRects[0]!.width).toBeCloseTo(292.5)
- expect(starredGridRect.right - starredCardRects.at(-1)!.right).toBeCloseTo(32)
- expect(appCardRects.map(({ left, width }) => ({ left, width }))).toEqual(
- starredCardRects.map(({ left, width }) => ({ left, width })),
- )
-
- const narrowGrid = screen.getByRole('region', { name: 'Narrow card grid' })
- const narrowGridElement = narrowGrid.element()
- const narrowCardRects = narrowGrid
- .getByRole('article')
- .elements()
- .map((element) => element.getBoundingClientRect())
-
- expect(new Set(narrowCardRects.map((rect) => rect.top)).size).toBe(4)
- expect(narrowCardRects.every((rect) => Math.abs(rect.width - 280) < 0.1)).toBe(true)
- expect(narrowGridElement.scrollWidth).toBe(narrowGridElement.clientWidth)
- })
-})
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-catalog-alignment.browser.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-catalog-alignment.browser.spec.tsx
deleted file mode 100644
index 3e1f3117bd4..00000000000
--- a/web/app/components/plugins/marketplace/home/__tests__/home-catalog-alignment.browser.spec.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { render } from 'vitest-browser-react'
-import HomeCatalogNavigation from '../home-catalog-navigation'
-import HomeCatalogTabs from '../home-catalog-tabs'
-import { HomeStickyStateProvider } from '../home-sticky-state-provider'
-import styles from '../home-sticky.module.css'
-
-describe('Marketplace home catalog alignment', () => {
- it('aligns catalog tabs and filters with the content container', async () => {
- const screen = await render(
- <HomeStickyStateProvider>
- <div className="w-[1200px]" data-marketplace-standalone>
- <HomeCatalogNavigation
- isMarketplacePlatform
- catalogCategories={
- <div data-testid="catalog-filter" role="group" aria-label="Categories" />
- }
- catalogTabs={
- <HomeCatalogTabs
- isMarketplacePlatform
- labels={{ plugins: 'Plugins', templates: 'Templates' }}
- />
- }
- />
- <div className={`px-8 ${styles.catalogContent}`}>
- <div role="region" aria-label="Catalog content" className="h-10" />
- </div>
- </div>
- </HomeStickyStateProvider>,
- )
-
- const contentLeft = screen
- .getByRole('region', { name: 'Catalog content' })
- .element()
- .getBoundingClientRect().left
- const tabsLeft = screen.getByRole('navigation').element().getBoundingClientRect().left
- const filtersLeft = screen.getByTestId('catalog-filter').element().getBoundingClientRect().left
-
- expect(tabsLeft).toBeCloseTo(contentLeft)
- expect(filtersLeft).toBeCloseTo(contentLeft)
- })
-})
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-catalog-handoff.browser.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-catalog-handoff.browser.spec.tsx
index 25b68060190..a16eed45746 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/home-catalog-handoff.browser.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/home-catalog-handoff.browser.spec.tsx
@@ -83,8 +83,6 @@ describe('Marketplace catalog tab handoff', () => {
expect(initialHeaderSlotWidth).toBeGreaterThan(0)
expect(initialHeaderSlotHeight).toBeGreaterThan(0)
expect(getComputedStyle(headerTabsSlot).pointerEvents).toBe('none')
- expect(getComputedStyle(headerTabsSlot).transitionProperty).toBe('opacity, transform')
- expect(getComputedStyle(headerTabsSlot).transitionDuration).toBe('0.14s')
contentPluginsLink.focus()
expect(document.activeElement).toBe(contentPluginsLink)
@@ -99,7 +97,6 @@ describe('Marketplace catalog tab handoff', () => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
)
- expect(navigation).not.toHaveClass(styles.catalogNavigationPinned!)
expect(scrollContainer.scrollTop).toBe(handoffScrollTop - 1)
expect(
contentTabsRegion.getBoundingClientRect().bottom - header.getBoundingClientRect().bottom,
@@ -112,9 +109,7 @@ describe('Marketplace catalog tab handoff', () => {
scrollContainer.scrollTop = handoffScrollTop
scrollContainer.dispatchEvent(new Event('scroll'))
- await vi.waitFor(() => {
- expect(navigation).toHaveClass(styles.catalogNavigationPinned!)
- })
+ await expect.poll(() => contentTabsSlot.hasAttribute('inert')).toBe(true)
expect(scrollContainer.scrollTop).toBe(handoffScrollTop)
expect(navigation.getBoundingClientRect().height).toBeCloseTo(initialHeight)
@@ -133,8 +128,6 @@ describe('Marketplace catalog tab handoff', () => {
expect(scrollContainer.scrollHeight).toBe(initialScrollHeight)
expect(getComputedStyle(contentTabsSlot).display).not.toBe('none')
expect(getComputedStyle(contentTabsSlot).pointerEvents).toBe('none')
- expect(getComputedStyle(contentTabsSlot).transitionProperty).toBe('opacity, transform')
- expect(getComputedStyle(contentTabsSlot).transitionDuration).toBe('0.14s')
expect(contentTabsSlot).toHaveAttribute('aria-hidden', 'true')
expect(contentTabsSlot).toHaveAttribute('inert')
expect(headerTabsSlot).not.toHaveAttribute('aria-hidden')
@@ -155,7 +148,6 @@ describe('Marketplace catalog tab handoff', () => {
expect(document.activeElement).toBe(contentPluginsLink)
})
- expect(navigation).not.toHaveClass(styles.catalogNavigationPinned!)
expect(scrollContainer.scrollTop).toBe(handoffScrollTop - 1)
expect(
contentTabsRegion.getBoundingClientRect().bottom - header.getBoundingClientRect().bottom,
@@ -194,7 +186,6 @@ describe('Marketplace catalog tab handoff', () => {
)
const scrollContainer = document.getElementById(MARKETPLACE_CONTAINER_ID)!
- const navigation = screen.getByRole('region').element()
const contentTabsSlot = screen.getByTestId('mobile-content-tabs').element().parentElement!
const headerTabs = screen.getByTestId('mobile-header-tabs').element()
const headerTabsSlot = headerTabs.parentElement!
@@ -204,7 +195,6 @@ describe('Marketplace catalog tab handoff', () => {
scrollContainer.scrollTop = 300
scrollContainer.dispatchEvent(new Event('scroll'))
- expect(navigation).not.toHaveClass(styles.catalogNavigationPinned!)
expect(contentTabsSlot).not.toHaveAttribute('aria-hidden')
expect(contentTabsSlot).not.toHaveAttribute('inert')
expect(getComputedStyle(contentTabsSlot).opacity).toBe('1')
@@ -220,9 +210,7 @@ describe('Marketplace catalog tab handoff', () => {
)
await page.viewport(880, 800)
- await vi.waitFor(() => {
- expect(navigation).toHaveClass(styles.catalogNavigationPinned!)
- })
+ await expect.poll(() => contentTabsSlot.hasAttribute('inert')).toBe(true)
expect(getComputedStyle(headerTabs).display).toBe('flex')
expect(contentTabsSlot).toHaveAttribute('aria-hidden', 'true')
expect(contentTabsSlot).toHaveAttribute('inert')
@@ -230,9 +218,7 @@ describe('Marketplace catalog tab handoff', () => {
expect(headerTabsSlot).not.toHaveAttribute('inert')
await page.viewport(879, 800)
- await vi.waitFor(() => {
- expect(navigation).not.toHaveClass(styles.catalogNavigationPinned!)
- })
+ await expect.poll(() => contentTabsSlot.hasAttribute('inert')).toBe(false)
expect(contentTabsSlot).not.toHaveAttribute('aria-hidden')
expect(contentTabsSlot).not.toHaveAttribute('inert')
expect(headerTabsSlot).toHaveAttribute('aria-hidden', 'true')
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-search-mobile-layout.browser.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-search-mobile-layout.browser.spec.tsx
index ba85fb0b0de..cc9fe075aed 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/home-search-mobile-layout.browser.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/home-search-mobile-layout.browser.spec.tsx
@@ -1,11 +1,9 @@
import { page } from 'vite-plus/test/browser'
import { render } from 'vitest-browser-react'
import { MARKETPLACE_CONTAINER_ID } from '../../constants'
-import { HOME_SEARCH_MOBILE_PADDING_BOTTOM_PX } from '../home-constants'
import HomeHeader from '../home-header'
import HomeSearch from '../home-search'
import { HomeShell } from '../home-shell'
-import styles from '../home-sticky.module.css'
vi.mock('../home-catalog-tabs', () => ({
default: () => null,
@@ -88,29 +86,6 @@ describe('Marketplace mobile search layout', () => {
expect(isCenterClickable(searchInput)).toBe(true)
})
- it('keeps bottom padding under the stuck mobile search', async () => {
- await page.viewport(390, 844)
- const screen = await renderMarketplaceHome()
-
- const scrollContainer = document.getElementById(MARKETPLACE_CONTAINER_ID)!
- const searchInput = screen
- .getByRole('textbox', { name: 'Search plugins or templates' })
- .element()
-
- scrollContainer.scrollTop = 400
- scrollContainer.dispatchEvent(new Event('scroll'))
- await nextFrame()
-
- const searchRow = document.querySelector(`.${styles.search}`)!
- const inputRect = searchInput.getBoundingClientRect()
- const rowRect = searchRow.getBoundingClientRect()
-
- expect(getComputedStyle(searchRow).paddingBottom).toBe(
- `${HOME_SEARCH_MOBILE_PADDING_BOTTOM_PX}px`,
- )
- expect(rowRect.bottom - inputRect.bottom).toBeCloseTo(HOME_SEARCH_MOBILE_PADDING_BOTTOM_PX, 0)
- })
-
it('keeps the desktop search in the header gap while scrolling', async () => {
await page.viewport(1280, 900)
const screen = await renderMarketplaceHome()
@@ -128,7 +103,6 @@ describe('Marketplace mobile search layout', () => {
expect(
searchInput.getBoundingClientRect().top - header.getBoundingClientRect().top,
).toBeCloseTo(6, 0)
- expect(getComputedStyle(document.querySelector(`.${styles.search}`)!).paddingBottom).toBe('0px')
})
it('keeps a search-results search below the header when there is no hero to overlap', async () => {
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-trending-layout.browser.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-trending-layout.browser.spec.tsx
index b816cf7fda7..6c471814b1f 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/home-trending-layout.browser.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/home-trending-layout.browser.spec.tsx
@@ -227,20 +227,6 @@ describe('Marketplace home trending layout', () => {
expect(getComputedStyle(artwork!).objectPosition).toBe('0% 50%')
})
- it('keeps the blog artwork left corners rounded when its image is cropped', async () => {
- const screen = await render(
- <div className="w-[600px]">
- <HomeBannerSlide banner={blogBanner} isMarketplacePlatform page="plugins" />
- </div>,
- )
-
- const artwork = screen.getByRole('link').element().querySelector('img')
-
- expect(artwork).not.toBeNull()
- expect(getComputedStyle(artwork!).borderTopLeftRadius).toBe('16px')
- expect(getComputedStyle(artwork!).borderBottomLeftRadius).toBe('16px')
- })
-
it('wraps from the last banner back to the first visible slide', async () => {
const screen = await render(
<HomeTrending banners={carouselBanners} isMarketplacePlatform page="plugins" />,
diff --git a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.browser.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.browser.spec.tsx
index eb9a78b6ec6..be1e8b7ea1b 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.browser.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.browser.spec.tsx
@@ -164,143 +164,4 @@ describe('Marketplace search autocomplete layout', () => {
expect(input.element().getBoundingClientRect().top).toBeCloseTo(inputTopBefore)
expect(catalogNavigation.getBoundingClientRect().top).toBeCloseTo(navigationTopBefore)
})
-
- it('matches the reference grouped panel and compact result spacing', async () => {
- await page.viewport(1280, 720)
- mockTemplateSearch.mockResolvedValue({
- data: {
- templates: [
- {
- id: 'template-1',
- template_name: 'Legal Research Agent',
- overview: 'Research legal questions with cited sources.',
- publisher_handle: 'dify',
- usage_count: 120,
- categories: ['knowledge'],
- icon: '📄',
- icon_background: '#FFFFFF',
- icon_file_key: '',
- },
- {
- id: 'template-2',
- template_name: 'Contract Reviewer',
- overview: 'Review contracts and identify risks.',
- publisher_handle: 'dify',
- usage_count: 80,
- categories: ['knowledge'],
- icon: '📄',
- icon_background: '#FFFFFF',
- icon_file_key: '',
- },
- ],
- total: 2,
- },
- })
-
- const screen = await render(
- <Wrapper>
- <div className="w-[420px]">
- <StickyTemplateSearch />
- </div>
- </Wrapper>,
- )
-
- await screen.getByRole('combobox', { name: 'Search templates' }).fill('legal')
- await expect.element(screen.getByText('Legal Research Agent')).toBeVisible()
-
- const input = screen.getByRole('combobox', { name: 'Search templates' }).element()
- const searchBox = input.parentElement!
- const list = screen.getByRole('listbox').element()
- const panel = list.parentElement!
- const templateGroup = screen.getByRole('group', { name: 'Templates' }).element()
- const firstItem = screen.getByRole('option', { name: /Legal Research Agent/ }).element()
- const lastItem = screen.getByRole('option', { name: /Contract Reviewer/ }).element()
- const panelStyle = getComputedStyle(panel)
- const listStyle = getComputedStyle(list)
- const templateGroupStyle = getComputedStyle(templateGroup)
- const firstItemStyle = getComputedStyle(firstItem)
- const statusRoots = screen.getByRole('status').all()
- const trailingStatus = statusRoots.at(-1)!.element()
-
- expect(
- Math.abs(panel.getBoundingClientRect().width - searchBox.getBoundingClientRect().width),
- ).toBeLessThanOrEqual(16)
- expect(panelStyle.paddingTop).toBe('0px')
- expect(panelStyle.paddingRight).toBe('0px')
- expect(panelStyle.paddingBottom).toBe('0px')
- expect(panelStyle.paddingLeft).toBe('0px')
- expect(panelStyle.borderRadius).toBe('12px')
- expect(listStyle.paddingTop).toBe('0px')
- expect(templateGroupStyle.paddingTop).toBe('4px')
- expect(templateGroupStyle.paddingRight).toBe('4px')
- expect(templateGroupStyle.paddingBottom).toBe('4px')
- expect(templateGroupStyle.paddingLeft).toBe('4px')
- expect(firstItemStyle.paddingTop).toBe('4px')
- expect(firstItemStyle.paddingRight).toBe('4px')
- expect(firstItemStyle.paddingBottom).toBe('4px')
- expect(firstItemStyle.paddingLeft).toBe('12px')
- expect(firstItemStyle.borderRadius).toBe('8px')
- expect(firstItemStyle.marginLeft).toBe('0px')
- expect(firstItemStyle.marginRight).toBe('0px')
- expect(trailingStatus.getBoundingClientRect().height).toBe(0)
- expect(
- panel.getBoundingClientRect().bottom - lastItem.getBoundingClientRect().bottom,
- ).toBeCloseTo(5)
- })
-
- it('keeps result rows fully clickable without a persistent trailing arrow', async () => {
- await page.viewport(390, 844)
- mockTemplateSearch.mockResolvedValue({
- data: {
- templates: [
- {
- id: 'template-1',
- template_name: 'Legal Research Agent',
- overview: 'Research legal questions with cited sources.',
- publisher_handle: 'dify',
- usage_count: 120,
- categories: ['knowledge'],
- icon: '📄',
- icon_background: '#FFFFFF',
- icon_file_key: '',
- },
- ],
- total: 1,
- },
- })
-
- const screen = await render(
- <Wrapper>
- <div className="w-full px-4">
- <StickyTemplateSearch />
- </div>
- </Wrapper>,
- )
-
- await screen.getByRole('combobox', { name: 'Search templates' }).fill('legal')
- const result = screen.getByRole('option', { name: /Legal Research Agent/ })
- await expect.element(result).toBeVisible()
-
- const resultElement = result.element()
- const resultRect = resultElement.getBoundingClientRect()
- const label = screen.getByText('Legal Research Agent').element()
- const labelRectBeforeHover = label.getBoundingClientRect()
- const trailingVisuals = Array.from(
- resultElement.querySelectorAll<HTMLElement>('[aria-hidden="true"]'),
- ).filter((element) => {
- const rect = element.getBoundingClientRect()
- return rect.width > 0 && rect.left >= resultRect.right - 40
- })
-
- expect(trailingVisuals).toHaveLength(0)
- expect(getComputedStyle(resultElement).cursor).toBe('pointer')
-
- const backgroundBeforeHover = getComputedStyle(resultElement).backgroundColor
- await result.hover()
- const labelRectAfterHover = label.getBoundingClientRect()
-
- expect(getComputedStyle(resultElement).backgroundColor).not.toBe(backgroundBeforeHover)
- expect(labelRectAfterHover.left).toBeCloseTo(labelRectBeforeHover.left)
- expect(labelRectAfterHover.width).toBeCloseTo(labelRectBeforeHover.width)
- })
})
diff --git a/web/app/components/workflow/block-selector/README.md b/web/app/components/workflow/block-selector/README.md
index 1b6a5fd58d3..86622f2bda5 100644
--- a/web/app/components/workflow/block-selector/README.md
+++ b/web/app/components/workflow/block-selector/README.md
@@ -51,4 +51,6 @@ Tests protect observable behavior through public interfaces:
- independent per-tab session state and reset after close;
- disabled behavior and selection side effects.
-Do not assert utility classes, child indexes, component implementation details, or third-party primitive internals. Use `userEvent` and semantic queries. Verify geometry, clipped focus indicators, hover/focus reveal, and real browser focus order in Browser Mode or E2E rather than happy-dom.
+Do not assert utility classes, child indexes, component implementation details, or third-party primitive internals. Use `userEvent` and semantic queries. Follow the [Web testing policy] when deciding whether browser verification needs permanent coverage.
+
+[Web testing policy]: ../../../../docs/test.md#browser-mode-admission
diff --git a/web/docs/test.md b/web/docs/test.md
index 9a36403c08a..cacb5b80eae 100644
--- a/web/docs/test.md
+++ b/web/docs/test.md
@@ -15,7 +15,7 @@ Write or update a test when a change affects a stable, observable contract:
Do not add tests merely for file/prop coverage, render-without-crashing checks, React implementation choices, or inputs excluded by TypeScript and the product contract.
-For visual-only changes, verify the real UI at representative widths and states. Use browser, screenshot, Storybook, or end-to-end coverage when the risk justifies automation.
+Decide whether a regression needs lasting automated coverage before choosing its boundary or runtime. Check existing tests first. For visual-only changes, default to reviewing the real UI at representative widths and states; record the result without adding a permanent test. Automate a stable visual requirement or meaningful regression risk, not every design adjustment. Do not move a low-value test to another runner or a screenshot suite merely to keep coverage.
### Coverage
@@ -29,24 +29,26 @@ Use the smallest boundary that includes the behavior owner and proves the produc
- Test hooks directly only when the hook itself exposes a reusable public contract. Otherwise, exercise the hook through its owning component or feature.
- Use React Testing Library for component and feature behavior visible through the DOM or external side effects.
- Use integration tests for behavior that crosses meaningful module boundaries.
-- Use the `browser` project only for browser-owned behavior that `happy-dom` cannot represent faithfully.
+- Use the `browser` project when it adds meaningful browser evidence under [Browser Mode Admission].
- Follow the [Dify UI testing contract] for the Storybook and Vitest boundary of Dify UI primitives.
Test the behavior owner. Barrel exports, pass-through wrappers, and purely presentational children do not need separate tests when the owning feature already proves their contract. Do not repeat generic behavior already owned by Base UI, React Aria, or the browser; test Dify's integration, overrides, and known regressions.
### Browser Mode Admission
-`happy-dom` is the default choice for tests under `web/`. Use the `unit` project for pure logic, hooks, and DOM-observable component or feature behavior that does not depend on browser-owned behavior. This split follows [Vitest test projects] and [Why Browser Mode].
+Web defaults to the `unit` project in `happy-dom`. This is a project tradeoff, not a Vitest restriction: [Vitest component testing] recommends Browser Mode, and [Vitest visual regression testing] supports visual contracts.
-First choose the test scope by the behavior owner, then choose the project by the environment needed to prove the asserted contract—not by an interaction label such as "focus," "keyboard," or "pointer." Use the `unit` project for Dify-owned markup, event handling, and DOM-observable state when `@testing-library/user-event`'s simulation is sufficient for the asserted result. For example, `user.tab()` can protect a focus sequence encoded by simple semantic markup when the assertion is determined by DOM order, disabled state, and `tabindex`; it does not validate the browser's native sequential focus navigation. See the [Testing Library user-event convenience APIs].
+A new browser test must establish all three:
-Use the `browser` project only when you can name a browser-owned failure that `happy-dom` could miss, such as:
+- **Value:** name the user-visible failure or stable visual requirement worth protecting. Layout, focus, portals, observers, and “happy-dom cannot do this” alone are not justification.
+- **Additional evidence:** identify what existing owner tests miss and what real rendering or browser interaction adds. Do not repeat a state matrix just because a browser fixture exists.
+- **Faithful boundary:** exercise the production owner and assert the claimed result. A copied layout cannot prove page integration; cursor or hover styling cannot prove that clicking performs an action.
-- CSS layout or rendered visibility changing geometry, hit testing, responsive behavior, or pointer targeting.
-- Native focus behavior or focus-event ordering changing because of browser-calculated focusability, `inert`, Shadow DOM traversal, or another browser default.
-- Selection, scrolling, real keyboard or pointer input, browser APIs, observers, or animation lifecycles whose native implementation changes the result.
+Use the smallest scenario that supplies that evidence. Native selection, focus restoration to CSS-hidden controls, hit testing, scrolling, and animation completion can justify browser coverage. Ordinary event handling and DOM state usually belong in `unit`. Synthetic events can test handler responses but do not prove native gesture generation, capture, or event ordering; use the [Vitest Interactivity API] when those are the contract.
-A portal, focus trap, shadow root, observer, or interaction label alone does not justify Browser Mode, nor does reducing mocks or raising coverage. Each `*.browser.spec.{ts,tsx}` test under `web/app/` must exercise the smallest owner through semantic locators and identify the browser-owned result that justifies its runtime. Do not use forced interaction, fixed sleeps, private DOM assertions, or real network requests.
+Do not add permanent tests solely to freeze decorative spacing, radii, or artwork dimensions from a one-off visual adjustment. Geometry and computed styles are appropriate when they prove the chosen contract, such as readable content, unobstructed controls, or visible keyboard focus. Visual baselines need an explicit stable requirement and controlled rendering environment.
+
+Each `*.browser.spec.{ts,tsx}` must make its regression and additional evidence clear from its scenario and assertions; add a short explanation only when needed. Do not use forced interaction, fixed sleeps, private DOM assertions, or real network requests.
Browser Mode remains a focused component or feature test and currently proves Chromium only. Use the end-to-end suite for a running application, authentication, real routing, backend APIs, persistence, or complete journeys.
@@ -59,8 +61,8 @@ Browser Mode remains a focused component or feature test and currently proves Ch
- Test referential identity only when identity is itself a documented public contract.
- One test should describe one behavior. It may contain multiple assertions when they jointly prove that behavior.
- Test only input states supported by the type and product contract. Do not manufacture `null`, `undefined`, or extreme values without a reachable scenario.
-- Do not assert CSS class names. Verify relevant styling through rendered visibility, geometry, focus indicators, or visual review instead of locking tests to utility strings.
-- Use snapshots only when serialized output is itself an intentionally public, stable contract.
+- Do not assert CSS class names or mechanically translate them into computed-style assertions. Assert the required outcome; use visual review for incidental styling.
+- Use DOM or data snapshots only when serialized output is itself an intentionally public, stable contract. Visual baselines follow Browser Mode Admission.
## Queries, Interaction, and Accessibility
@@ -157,6 +159,7 @@ Always pass `--project unit` or `--project browser`. Bare `vp test` runs both re
- [Testing Library user-event guidance]
- [Testing Library user-event convenience APIs]
+[Browser Mode Admission]: #browser-mode-admission
[Dify UI testing contract]: ../../packages/dify-ui/docs/testing.md
[React Testing Library documentation]: https://testing-library.com/docs/react-testing-library/intro
[Storybook Vitest addon]: https://storybook.js.org/docs/writing-tests/integrations/vitest-addon
@@ -168,7 +171,10 @@ Always pass `--project unit` or `--project browser`. Bare `vp test` runs both re
[Vitest Browser Mode documentation]: https://v4.vitest.dev/guide/browser
[Vitest Browser Mode locators]: https://v4.vitest.dev/api/browser/locators
[Vitest Browser Mode traces]: https://v4.vitest.dev/guide/browser/trace-view
+[Vitest Interactivity API]: https://v4.vitest.dev/api/browser/interactivity
+[Vitest component testing]: https://v4.vitest.dev/guide/browser/component-testing
[Vitest documentation]: https://v4.vitest.dev/guide
[Vitest test projects]: https://v4.vitest.dev/guide/projects
+[Vitest visual regression testing]: https://v4.vitest.dev/guide/browser/visual-regression-testing
[Why Browser Mode]: https://v4.vitest.dev/guide/browser/why
[static checks]: lint.md