Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
langgenius avatar

Frontend Testing

  • 3.2k installs
  • 151k repo stars
  • Updated August 5, 2026
  • langgenius/dify

frontend-testing is an agent skill that generates Vitest and React Testing Library tests for Dify frontend components, hooks, and utilities following web/docs/test.md conventions.

About

frontend-testing is a Codex-oriented Dify skill for generating Vitest and React Testing Library tests for components, hooks, and utilities across the web codebase. It is derived from the authoritative web/docs/test.md and mandates Vitest mock and timer APIs via vi.* instead of ad-hoc jest patterns. The skill triggers on testing, spec files, coverage, Vitest, RTL, unit tests, integration tests, and write or review test requests while excluding backend pytest and Cucumber Playwright E2E under e2e/. Test files use ComponentName.spec.tsx inside sibling __tests__ directories mapped from source paths such as foo/index.tsx to foo/__tests__/index.spec.tsx. Required describe blocks cover Rendering, Props, User Interactions, and Edge Cases with vi.clearAllMocks in beforeEach. External dependencies mock via vi.mock while project components import real modules. Commands run from web/ with pnpm test, watch mode, coverage, and pnpm analyze-component for complexity review. Developers reach for frontend-testing when adding or reviewing Dify frontend tests and need repo-specific conventions rather than generic React Testing Library advice.

  • Authoritative source is web/docs/test.md with Vitest vi.* mock and timer APIs required.
  • Test files live in sibling __tests__/ folders as ComponentName.spec.tsx beside the source under test.
  • Required describe blocks cover Rendering, Props, User Interactions, and Edge Cases with beforeEach mock resets.
  • Mocks external dependencies only; project components and Zustand stores use real modules with setState in tests.
  • Excludes backend pytest and Cucumber Playwright E2E; commands run from web/ via pnpm test and analyze-component.

Frontend Testing by the numbers

  • 3,188 all-time installs (skills.sh)
  • +84 installs in the week ending Aug 5, 2026 (Skillselion tracking)
  • Ranked #308 of 2,153 Testing & QA skills by installs in the Skillselion catalog
  • Security screen: LOW risk (skills.sh audit)
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
At a glance

frontend-testing capabilities & compatibility

Capabilities
vitest and rtl test scaffolding for components a · __tests__/ placement and naming conventions · mock versus real import rules for dify modules · pnpm test and analyze component workflow guidanc
Use cases
testing · frontend
npx skills add https://github.com/langgenius/dify --skill frontend-testing

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs3.2k
repo stars151k
Security audit3 / 3 scanners passed
Last updatedAugust 5, 2026
Repositorylanggenius/dify

How do I write or review Dify frontend tests that follow project Vitest and RTL conventions instead of generic React testing patterns?

Invoke Dify's frontend-testing skill so your agent follows the project's UI test workflow instead of guessing checklists.

Who is it for?

Developers working in the Dify web monorepo who need agent-guided Vitest and RTL tests aligned with established project rules.

Skip if: Skip for backend pytest tests, Cucumber Playwright E2E under e2e/, or conceptual testing questions without code context.

When should I use this skill?

User writes or reviews Dify frontend tests, spec files, Vitest coverage, or React Testing Library component tests.

What you get

Spec files in __tests__/ folders with Rendering, Props, Interaction, and Edge Case coverage using vi.* mocks and real project components.

  • Vitest spec files
  • RTL component and hook tests

By the numbers

  • Authoritative test conventions sourced from web/docs/test.md

Files

SKILL.mdMarkdownGitHub ↗

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-component output 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.tsx inside 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.tsx maps to foo/__tests__/index.spec.tsx, and foo/bar.ts maps to foo/__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)
  describe('Props', () => {
    it('should apply custom className', () => {
      render(<Component className="custom" />)
      expect(screen.getByRole('button')).toHaveClass('custom')
    })
  })

  // 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:

1. Analyze & Plan: List all files, order by complexity (simple → complex) 1. Process ONE at a time: Write test → Run test → Fix if needed → Next 1. 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:

1. 🟢 Utility functions (simplest) 1. 🟢 Custom hooks 1. 🟡 Simple components (presentational) 1. 🟡 Medium components (state, effects) 1. 🔴 Complex components (API, routing) 1. 🔴 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.md for 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 index file)
  • 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 in web/test/nuqs-testing.tsx)
  • ✅ Assert URL synchronization via onUrlUpdate (searchParams, options.history)
  • ✅ For custom parsers (createParser), keep parse and serialize bijective 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 nuqs directly 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
  • Use semantic queries (getByRole with accessible name, getByLabelText, getByPlaceholderText, getByText, and scoped within(...))
  • Treat getByTestId as 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 on data-testid.
  • Remove production data-testid attributes 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)

1. Rendering: Component renders without crashing 1. Props: Required props, optional props, default values 1. Edge Cases: null, undefined, empty values, boundary conditions

Conditional (When Present)

FeatureTest Focus
useStateInitial state, transitions, cleanup
useEffectExecution, dependencies, cleanup
Event handlersAll onClick, onChange, onSubmit, keyboard
API callsLoading, success, error states
RoutingNavigation, params, query strings
useCallback/useMemoReferential equality
ContextProvider values, consumer behavior
FormsValidation, 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 practices
  • references/async-testing.md - Async operations and API calls
  • references/domain-components.md - Workflow, Dataset, Configuration testing
  • references/common-patterns.md - Frequently used testing patterns
  • references/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 tests
  • web/app/components/base/radio/__tests__/index.spec.tsx - Component tests
  • web/__mocks__/provider-context.ts - Mock factory example

Project Configuration

  • web/vite.config.ts - Vite/Vitest configuration
  • web/vitest.setup.ts - Test environment setup
  • web/scripts/analyze-component.js - Component analysis tool
  • Modules are not mocked automatically. Global mocks live in web/vitest.setup.ts (for example react-i18next, next/image); mock other modules like ky or mime locally in test files.

Related skills

How it compares

Use frontend-testing over generic Vitest skills when contributing to the Dify repo and tests must match project-specific web/docs/test.md rules.

FAQ

Where should Dify frontend test files live?

In a sibling __tests__/ folder as ComponentName.spec.tsx at the same level as the source file under test.

Should project components be mocked in Dify frontend tests?

No; import real project components and Zustand stores, mocking only external dependencies with vi.mock.

Is Frontend Testing safe to install?

skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

Testing & QAtestingfrontend

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.