frontend-testing
langgenius/dify
Generate Vitest + React Testing Library tests for Dify frontend components, hooks, and utilities.
What is frontend-testing?
This skill generates high-quality frontend tests for Dify using Vitest and React Testing Library, following the project's established conventions. Use it when writing, reviewing, or improving tests for React components, hooks, utilities, or when working with test coverage and Vitest-related tasks.
- Generate component, hook, and utility tests following AAA (Arrange-Act-Assert) pattern
- Create integration tests that import real project components and mock only external dependencies
- Test URL state synchronization for components using nuqs `useQueryState`
- Provide incremental testing workflow for complex multi-file directories
- Analyze component complexity and suggest refactoring before testing
How to install frontend-testing
npx skills add null --skill frontend-testing- Dify repository cloned locally
- Node.js and pnpm installed
- Familiarity with React Testing Library and Vitest basics
How to use frontend-testing
- 1.Run `pnpm analyze-component <path>` to assess component complexity and dependencies
- 2.Plan test order by complexity: utilities → hooks → simple components → complex components → integration tests
- 3.Write tests in `__tests__/` directory at same level as source file (e.g., `foo/index.tsx` → `foo/__tests__/index.spec.tsx`)
- 4.Run `pnpm test <file>.spec.tsx` to verify each test passes before moving to next file
- 5.Use `pnpm test --coverage` to check coverage and identify untested code paths
- 6.For URL state components, use `NuqsTestingAdapter` to verify query synchronization
Use cases
- Write tests for a new React component or custom hook in the Dify frontend
- Review existing tests for completeness and coverage gaps
- Improve test coverage for a directory of related components
- Create integration tests that verify component interactions with real child components
- Test query state behavior in components using nuqs for URL synchronization
- Frontend developers working on Dify React components
- QA engineers improving test coverage
- Developers reviewing or refactoring existing component test suites
- Contributors adding new features to the Dify web interface
frontend-testing FAQ
Test files must live in a sibling `__tests__/` directory at the same level as the source. For example, `foo/index.tsx` maps to `foo/__tests__/index.spec.tsx`, and `foo/bar.ts` maps to `foo/__tests__/bar.spec.ts`.
No. Only mock external dependencies like API services (`@/service/*`), `next/navigation`, and complex context providers. Always import real project components, including base components and sibling/child components in the same directory.
Never generate all tests at once. For each file: write test → run `pnpm test <file>.spec.tsx` → verify it passes → move to next file. Process files in order of complexity: utilities, hooks, simple components, complex components, then integration tests.
Use `NuqsTestingAdapter` from `web/test/nuqs-testing.tsx`. Assert URL synchronization via `onUrlUpdate`, verify default-clearing behavior, and test custom parsers with round-trip edge cases like `%2F`, `%25`, and spaces.
Refactor first if component complexity exceeds 50, file size exceeds 500 lines, or there are many dependencies. Break complex components into smaller pieces or extract logic into hooks before writing tests.
Full instructions (SKILL.md)
Source of truth, from langgenius/dify.
name: frontend-testing description: Generate Vitest + React Testing Library tests for Dify frontend components, hooks, and utilities. Triggers on testing, spec files, coverage, Vitest, RTL, unit tests, integration tests, or write/review test requests.
Dify Frontend Testing Skill
This skill enables Codex to generate high-quality, comprehensive frontend tests for the Dify project following established conventions and best practices.
⚠️ Authoritative Source: This skill is derived from
web/docs/test.md. Use Vitest mock/timer APIs (vi.*).
When to Apply This Skill
Apply this skill when the user:
- Asks to write tests for a component, hook, or utility
- Asks to review existing tests for completeness
- Mentions Vitest, React Testing Library, RTL, or spec files
- Requests test coverage improvement
- Uses
pnpm analyze-componentoutput as context - Mentions testing, unit tests, or integration tests for frontend code
- Wants to understand testing patterns in the Dify codebase
Do NOT apply when:
- User is asking about backend/API tests (Python/pytest)
- User is asking about E2E tests (Cucumber + Playwright under
e2e/) - User is only asking conceptual questions without code context
Quick Reference
Key Commands
Run these commands from web/. From the repository root, prefix them with pnpm -C web.
# Run all tests
pnpm test
# Watch mode
pnpm test --watch
# Run specific file
pnpm test path/to/file.spec.tsx
# Generate coverage report
pnpm test --coverage
# Analyze component complexity
pnpm analyze-component <path>
# Review existing test
pnpm analyze-component <path> --review
File Naming
- Test files:
ComponentName.spec.tsxinside a same-level__tests__/directory - Placement rule: Component, hook, and utility tests must live in a sibling
__tests__/folder at the same level as the source under test. For example,foo/index.tsxmaps tofoo/__tests__/index.spec.tsx, andfoo/bar.tsmaps tofoo/__tests__/bar.spec.ts. - Integration tests:
web/__tests__/directory
Test Structure Template
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import Component from './index'
// ✅ Import real project components (DO NOT mock these)
// import Loading from '@/app/components/base/loading'
// import { ChildComponent } from './child-component'
// ✅ Mock external dependencies only
vi.mock('@/service/api')
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
usePathname: () => '/test',
}))
// ✅ Zustand stores: Use real stores (auto-mocked globally)
// Set test state with: useAppStore.setState({ ... })
// Shared state for mocks (if needed)
let mockSharedState = false
describe('ComponentName', () => {
beforeEach(() => {
vi.clearAllMocks() // ✅ Reset mocks BEFORE each test
mockSharedState = false // ✅ Reset shared state
})
// Rendering tests (REQUIRED)
describe('Rendering', () => {
it('should render without crashing', () => {
// Arrange
const props = { title: 'Test' }
// Act
render(<Component {...props} />)
// Assert
expect(screen.getByText('Test')).toBeInTheDocument()
})
})
// Props tests (REQUIRED when props change observable behavior)
describe('Props', () => {
it('should disable the action when disabled', () => {
render(<Component disabled />)
expect(screen.getByRole('button')).toBeDisabled()
})
})
// User Interactions
describe('User Interactions', () => {
it('should handle click events', () => {
const handleClick = vi.fn()
render(<Component onClick={handleClick} />)
fireEvent.click(screen.getByRole('button'))
expect(handleClick).toHaveBeenCalledTimes(1)
})
})
// Edge Cases (REQUIRED)
describe('Edge Cases', () => {
it('should handle null data', () => {
render(<Component data={null} />)
expect(screen.getByText(/no data/i)).toBeInTheDocument()
})
it('should handle empty array', () => {
render(<Component items={[]} />)
expect(screen.getByText(/empty/i)).toBeInTheDocument()
})
})
})
Testing Workflow (CRITICAL)
⚠️ Incremental Approach Required
NEVER generate all test files at once. For complex components or multi-file directories:
- Analyze & Plan: List all files, order by complexity (simple → complex)
- Process ONE at a time: Write test → Run test → Fix if needed → Next
- Verify before proceeding: Do NOT continue to next file until current passes
For each file:
┌────────────────────────────────────────┐
│ 1. Write test │
│ 2. Run: pnpm test <file>.spec.tsx │
│ 3. PASS? → Mark complete, next file │
│ FAIL? → Fix first, then continue │
└────────────────────────────────────────┘
Complexity-Based Order
Process in this order for multi-file testing:
- 🟢 Utility functions (simplest)
- 🟢 Custom hooks
- 🟡 Simple components (presentational)
- 🟡 Medium components (state, effects)
- 🔴 Complex components (API, routing)
- 🔴 Integration tests (index files - last)
When to Refactor First
- Complexity > 50: Break into smaller pieces before testing
- 500+ lines: Consider splitting before testing
- Many dependencies: Extract logic into hooks first
📖 See
references/workflow.mdfor complete workflow details and todo list format.
Testing Strategy
Path-Level Testing (Directory Testing)
When assigned to test a directory/path, test ALL content within that path:
- Test all components, hooks, utilities in the directory (not just
indexfile) - Use incremental approach: one file at a time, verify each before proceeding
- Goal: 100% coverage of ALL files in the directory
Integration Testing First
Prefer integration testing when writing tests for a directory:
- ✅ Import real project components directly (including base components and siblings)
- ✅ Only mock: API services (
@/service/*),next/navigation, complex context providers - ❌ DO NOT mock base components (
@/app/components/base/*) or dify-ui primitives (@langgenius/dify-ui/*) - ❌ DO NOT mock sibling/child components in the same directory
See Test Structure Template for correct import/mock patterns.
nuqs Query State Testing (Required for URL State Hooks)
When a component or hook uses useQueryState / useQueryStates:
- ✅ Use
NuqsTestingAdapter(prefer shared helpers inweb/test/nuqs-testing.tsx) - ✅ Assert URL synchronization via
onUrlUpdate(searchParams,options.history) - ✅ For custom parsers (
createParser), keepparseandserializebijective and add round-trip edge cases (%2F,%25, spaces, legacy encoded values) - ✅ Verify default-clearing behavior (default values should be removed from URL when applicable)
- ⚠️ Only mock
nuqsdirectly when URL behavior is explicitly out of scope for the test
Core Principles
1. AAA Pattern (Arrange-Act-Assert)
Every test should clearly separate:
- Arrange: Setup test data and render component
- Act: Perform user actions
- Assert: Verify expected outcomes
2. Black-Box Testing
- Test observable behavior, not implementation details
- Test product contracts, not cosmetic implementation. Do not add or expand unit tests only to lock pure style classes, spacing, colors, backgrounds, or layout micro-adjustments. Cover visual-only fixes with browser/manual verification, screenshots, or E2E/visual checks when risk justifies it. Add unit tests only when the change affects user-observable behavior, accessibility semantics, state, data flow, routing, or a stable component API contract.
- Use semantic queries (
getByRolewith accessiblename,getByLabelText,getByPlaceholderText,getByText, and scopedwithin(...)) - Treat
getByTestIdas a last resort. If a control cannot be found by role/name, label, landmark, or dialog scope, fix the component accessibility first instead of adding or relying ondata-testid. - Remove production
data-testidattributes when semantic selectors can cover the behavior. Keep them only for non-visual mocked boundaries, editor/browser shims such as Monaco, canvas/chart output, or third-party widgets with no accessible DOM in the test environment. - Do not assert decorative icons by test id. Assert the named control that contains them, or mark decorative icons
aria-hidden. - Avoid testing internal state directly
- Prefer pattern matching over hardcoded strings in assertions:
// ❌ Avoid: hardcoded text assertions
expect(screen.getByText('Loading...')).toBeInTheDocument()
// ✅ Better: role-based queries
expect(screen.getByRole('status')).toBeInTheDocument()
// ✅ Better: pattern matching
expect(screen.getByText(/loading/i)).toBeInTheDocument()
3. Single Behavior Per Test
Each test verifies ONE user-observable behavior:
// ✅ Good: One behavior
it('should disable button when loading', () => {
render(<Button loading />)
expect(screen.getByRole('button')).toBeDisabled()
})
// ❌ Bad: Multiple behaviors
it('should handle loading state', () => {
render(<Button loading />)
expect(screen.getByRole('button')).toBeDisabled()
expect(screen.getByText('Loading...')).toBeInTheDocument()
expect(screen.getByRole('button')).toHaveClass('loading')
})
4. Semantic Naming
Use should <behavior> when <condition>:
it('should show error message when validation fails')
it('should call onSubmit when form is valid')
it('should disable input when isReadOnly is true')
Required Test Scenarios
Always Required (All Components)
- Rendering: Component renders without crashing
- Props: Required props, optional props, default values that change observable behavior. Do not test pass-through styling props such as
classNameunless they are an explicit, stable component API whose absence would break a real integration contract. - Edge Cases: null, undefined, empty values, boundary conditions
Conditional (When Present)
| Feature | Test Focus |
|---|---|
useState | Initial state, transitions, cleanup |
useEffect | Execution, dependencies, cleanup |
| Event handlers | All onClick, onChange, onSubmit, keyboard |
| API calls | Loading, success, error states |
| Routing | Navigation, params, query strings |
useCallback/useMemo | Referential equality |
| Context | Provider values, consumer behavior |
| Forms | Validation, submission, error display |
Coverage Goals (Per File)
For each test file generated, aim for:
- ✅ 100% function coverage
- ✅ 100% statement coverage
- ✅ >95% branch coverage
- ✅ >95% line coverage
Note: For multi-file directories, process one file at a time with full coverage each. See
references/workflow.md.
Detailed Guides
For more detailed information, refer to:
references/workflow.md- Incremental testing workflow (MUST READ for multi-file testing)references/mocking.md- Mock patterns, Zustand store testing, and best practicesreferences/async-testing.md- Async operations and API callsreferences/domain-components.md- Workflow, Dataset, Configuration testingreferences/common-patterns.md- Frequently used testing patternsreferences/checklist.md- Test generation checklist and validation steps
Authoritative References
Primary Specification (MUST follow)
web/docs/test.md- The canonical testing specification. This skill is derived from this document.
Reference Examples in Codebase
web/utils/classnames.spec.ts- Utility function testsweb/app/components/base/radio/__tests__/index.spec.tsx- Component testsweb/__mocks__/provider-context.ts- Mock factory example
Project Configuration
web/vite.config.ts- Vite/Vitest configurationweb/vitest.setup.ts- Test environment setupweb/scripts/analyze-component.js- Component analysis tool- Modules are not mocked automatically. Global mocks live in
web/vitest.setup.ts(for examplereact-i18next,next/image); mock other modules likekyormimelocally in test files.
Related skills
More from langgenius/dify and the wider catalog.
orpc-contract-first
Guide for implementing oRPC contract-first API patterns in Dify frontend. Trigger when creating or updating contracts in web/contract, wiring router composition, integrating TanStack Query with typed contracts, migrating legacy service calls to oRPC, or deciding whether to call queryOptions directly vs extracting a helper or use-* hook in web/service.
backend-code-review
Review backend code for quality, security, maintainability, and best practices.
component-refactoring
Refactor high-complexity React components in Dify frontend using extraction patterns and automated analysis.
frontend-code-review
Review Dify frontend code for correctness, accessibility, component design, and performance.

trading-quant
量化交易数据分析工具。A股/美股/港股/贵金属实时行情,多维度评分(技术面+资金面+基本面),涨跌停池,北向资金,分钟级资金流。Use when: (1) 查询任何股票实时行情和评分, (2) 分析A股涨跌停异动, (3) 查看北向资金流向, (4) 美股港股贵金属行情, (5) 全球市场概览, (6) 个股资金流分析。

lieflat-charts
Template-driven data visualization and report generation for HTML charts and multi-language reports with automatic color selection.