Frontend Testing Skill - Langflow
When to Apply
Activate this skill when:
- Writing new unit or integration tests for React components, hooks, utilities, or Zustand stores
- Reviewing existing tests for correctness, coverage, or best practices
- Improving test coverage for under-tested modules
- Debugging flaky or failing tests
- Refactoring test code for maintainability
Tech Stack
| Technology |
Version |
Purpose |
| Jest |
30.x |
Test runner and assertion framework |
| ts-jest |
29.x |
TypeScript transform for Jest |
| React Testing Library |
16.x |
Component rendering and DOM queries |
| @testing-library/user-event |
14.x |
Realistic user interaction simulation |
| @testing-library/jest-dom |
6.x |
Extended DOM matchers |
| jsdom |
(via jest-environment-jsdom 30.x) |
Browser environment simulation |
| React |
19.x |
UI framework |
| TypeScript |
5.4 |
Type safety |
| Zustand |
4.x |
State management |
| React Router DOM |
6.x |
Client-side routing |
| @tanstack/react-query |
5.x |
Server state management |
| Axios |
1.x |
HTTP client |
Project Configuration
- Jest config:
src/frontend/jest.config.js
- Setup files:
src/frontend/jest.setup.js (globals/mocks) and src/frontend/src/setupTests.ts (DOM matchers, ResizeObserver, IntersectionObserver, matchMedia)
- Path alias:
@/ maps to <rootDir>/src/
- Test match patterns:
src/**/__tests__/**/*.{test,spec}.{ts,tsx} and src/**/*.{test,spec}.{ts,tsx}
- Transform: Custom
transform-import-meta.js handles import.meta for Jest compatibility
- Global mocks (in
jest.setup.js): @radix-ui/react-form, react-markdown, remark-gfm, remark-math, rehype-mathjax/browser, lucide-react/dynamicIconImports, @/components/common/genericIconComponent, @/icons/BotMessageSquare, @/stores/darkStore, localStorage, sessionStorage, crypto
Key Commands
# Run all tests
npm test
# Run a specific test file
npm test -- path/to/file.test.tsx
# Run tests matching a pattern
npm test -- --testPathPattern="alertStore"
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
# Run a single test file with coverage
npm test -- --coverage --collectCoverageFrom='src/path/to/source.ts' path/to/__tests__/source.test.ts
File Naming and Location
Test files follow one of two patterns:
Dedicated __tests__ directory (preferred for components and modules):
src/components/core/my-component/
├── my-component.tsx
└── __tests__/
└── my-component.test.tsx
Co-located test file (acceptable for utilities and simple modules):
src/utils/
├── myUtil.ts
└── myUtil.test.ts
Naming convention: ComponentName.test.tsx for components, hook-name.test.ts for hooks, util-name.test.ts for utilities.
Do NOT use .spec.tsx -- while technically matched, the project convention is .test.tsx.
Test Structure Template
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import MyComponent from "../MyComponent";
// Mock dependencies (use jest.mock, NOT vi.mock)
jest.mock("@/controllers/API/api", () => ({
get: jest.fn(),
post: jest.fn(),
}));
describe("MyComponent", () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe("rendering", () => {
it("should render the component with default props", () => {
// Arrange
render(<MyComponent />);
// Act - (none for render test)
// Assert
expect(screen.getByRole("button", { name: /submit/i })).toBeInTheDocument();
});
});
describe("user interactions", () => {
it("should call onSubmit when the form is submitted", async () => {
// Arrange
const user = userEvent.setup();
const
render(<MyComponent />);
// Act
await user.click(screen.getByRole("button", { name: /submit/i }));
// Assert
expect(onSubmit).toHaveBeenCalledTimes(1);
});
});
});
Incremental Testing Workflow
When testing a directory with multiple files, follow this order:
- Identify all source files in the target directory
- Order by complexity (simplest first):
- Pure utility functions (no React, no side effects)
- Constants and configuration objects
- Custom hooks (no UI rendering)
- Simple presentational components (no state, no side effects)
- Stateful components with local state
- Components using Zustand stores
- Components with API calls or complex async behavior
- Integration-level components that compose many children
- For each file:
a. Read the source file completely
b. Identify all exported functions, components, and types
c. Write tests covering all branches and edge cases
d. Run the tests and fix any failures
e. Check coverage and add tests for uncovered lines
f. Move to the next file
- Run full directory coverage at the end to verify
Complexity-Based Test Ordering
Within a single test file, order test cases from simplest to most complex:
- Default rendering / initial state
- Props variations and conditional rendering
- User interactions (clicks, typing, form submission)
- Async operations (API calls, timers)
- Error states and edge cases
- Integration with stores or context
- Cleanup and unmount behavior
Core Principles
Arrange-Act-Assert (AAA)
Every test should have a clear three-phase structure. Use blank lines to separate each phase for readability.
Black-Box Testing
Test the component from the user's perspective. Query by role, label, text, or data-testid -- never by CSS class, internal state variable, or implementation detail.
Single Behavior Per Test
Each it() block should verify exactly one behavior. If you need to write "and" in the test name, split it into two tests.
Semantic Test Names
Use descriptive names that explain the expected behavior:
- Good:
"should disable the submit button when the form is invalid"
- Bad:
"button test" or "test 1"
Format: "should [expected behavior] when [condition]"
Required Test Scenarios
For every component, cover at minimum:
Rendering
- Default render with no optional props
- Render with all optional props provided
- Conditional rendering branches (if/else in JSX)
Props and State
- Each prop variation that changes rendered output
- Default prop values
- State transitions triggered by user actions
User Interactions
- Click handlers
- Form input and submission
- Keyboard navigation (if applicable)
- Hover/focus states (if applicable)
Challenge Tests (MANDATORY — not optional)
Happy path tests alone are NOT enough. They only confirm the code works when everything is perfect. Real bugs hide in the cracks. You MUST write tests that actively TRY TO BREAK the code:
Unexpected inputs:
null, undefined, "", [], {}, 0, -1, NaN, Infinity
- What happens when a required prop is missing?
- What happens when data from the API comes back with missing fields?
Boundary values:
- Max length strings (paste 10,000 chars in an input)
- Exactly at the limit, one past the limit
- Zero items, one item, maximum items
- First page, last page, out-of-range page
Malformed data:
- API returns
{ data: null } instead of { data: [] }
- JSON with extra unexpected fields
- Dates in wrong format, numbers as strings
Error states:
- Network failure (API rejects with 500)
- Authentication expired mid-action (401)
- Resource not found (404)
- Permission denied (403)
- Timeout
What should NOT happen:
- Verify that deleting a flow does NOT delete flows from other users
- Verify that a read-only user CANNOT trigger write mutations
- Verify that XSS payloads in user input are sanitized
Rapid/concurrent actions:
- Double-click on submit button
- Rapid repeated API calls
- Unmount component while async operation is in flight
Write tests based on REQUIREMENTS, not on what the source code does. This is how you catch bugs where the code diverges from expected behavior.
When a test fails: first ask if the CODE is wrong, not the test. Do NOT silently change a failing assertion to match the current code without understanding WHY.
Async Behavior
- Loading states
- Success states
- Error states
- Timeout/retry behavior
Coverage Goals
Per source file:
- Function coverage: 100%
- Branch coverage: > 95%
- Line coverage: > 95%
- Statement coverage: > 95%
Run coverage for a specific file:
npm test -- --coverage --collectCoverageFrom='src/path/to/file.ts' src/path/to/__tests__/file.test.ts
Important Rules
- Never use Vitest APIs: Use
jest.fn(), jest.mock(), jest.spyOn(), jest.mocked() -- never vi.* equivalents.
- Never mock base UI components from
@/components/ui/ -- render them as-is.
- Check
jest.setup.js before mocking: Many modules are already globally mocked (darkStore, genericIconComponent, react-markdown, radix-form, etc.). Do not re-mock them.
- Use
@testing-library/user-event over fireEvent for user interactions.
- Wrap state updates in
act() when testing Zustand stores or React state changes.
- Clean up after each test: Use
beforeEach(() => jest.clearAllMocks()) and afterEach for timers.
- Always write both happy path AND adversarial tests (null, undefined, empty values, boundary conditions, error states).
- Minimum coverage: 75% (target 80%). Below 75% the task is not complete.
Forbidden Test Anti-Patterns
| Pattern |
Problem |
How to Detect |
| The Liar |
Test passes but doesn't verify the behavior it claims to test |
Assertions don't match the test name |
| The Mirror |
Test reads source code and asserts exactly what the code does — finds zero bugs |
Test would never fail even if logic changes |
| The Giant |
50+ lines of setup, multiple acts, dozens of assertions |
Should be 5+ separate tests |
| The Mockery |
So many mocks that the test only tests the mock setup |
Count mocks — if > 3 deep, rethink |
| The Inspector |
Coupled to implementation details, breaks on any refactor |
Tests internal state instead of behavior |
| The Chain Gang |
Tests depend on execution order or share mutable state |
Tests fail when run in isolation |
| The Flaky |
Sometimes passes, sometimes fails with no code changes |
Non-deterministic assertions or timing issues |
References
- Incremental Testing Workflow - Step-by-step process for testing directories
- Mocking Guide - Patterns for mocking APIs, stores, routers, and context
- Async Testing - Patterns for async operations, timers, and waitFor
- Common Patterns - Query priority, events, forms, modals, data-driven tests
- Test Checklist - Pre-submission verification checklist
- Domain Components - Langflow-specific component testing patterns
- Component Template - Starter template for component tests
- Hook Template - Starter template for hook tests
- Utility Template - Starter template for utility tests
1---2name: frontend-testing3description: Frontend Testing Skill - Langflow4---5# Frontend Testing Skill - Langflow67## When to Apply89Activate this skill when:10- Writing new unit or integration tests for React components, hooks, utilities, or Zustand stores11- Reviewing existing tests for correctness, coverage, or best practices12- Improving test coverage for under-tested modules13- Debugging flaky or failing tests14- Refactoring test code for maintainability1516## Tech Stack1718| Technology | Version | Purpose |19|---|---|---|20| Jest | 30.x | Test runner and assertion framework |21| ts-jest | 29.x | TypeScript transform for Jest |22| React Testing Library | 16.x | Component rendering and DOM queries |23| @testing-library/user-event | 14.x | Realistic user interaction simulation |24| @testing-library/jest-dom | 6.x | Extended DOM matchers |25| jsdom | (via jest-environment-jsdom 30.x) | Browser environment simulation |26| React | 19.x | UI framework |27| TypeScript | 5.4 | Type safety |28| Zustand | 4.x | State management |29| React Router DOM | 6.x | Client-side routing |30| @tanstack/react-query | 5.x | Server state management |31| Axios | 1.x | HTTP client |3233## Project Configuration3435- **Jest config**: `src/frontend/jest.config.js`36- **Setup files**: `src/frontend/jest.setup.js` (globals/mocks) and `src/frontend/src/setupTests.ts` (DOM matchers, ResizeObserver, IntersectionObserver, matchMedia)37- **Path alias**: `@/` maps to `<rootDir>/src/`38- **Test match patterns**: `src/**/__tests__/**/*.{test,spec}.{ts,tsx}` and `src/**/*.{test,spec}.{ts,tsx}`39- **Transform**: Custom `transform-import-meta.js` handles `import.meta` for Jest compatibility40- **Global mocks** (in `jest.setup.js`): `@radix-ui/react-form`, `react-markdown`, `remark-gfm`, `remark-math`, `rehype-mathjax/browser`, `lucide-react/dynamicIconImports`, `@/components/common/genericIconComponent`, `@/icons/BotMessageSquare`, `@/stores/darkStore`, `localStorage`, `sessionStorage`, `crypto`4142## Key Commands4344```bash45# Run all tests46npm test4748# Run a specific test file49npm test -- path/to/file.test.tsx5051# Run tests matching a pattern52npm test -- --testPathPattern="alertStore"5354# Run tests in watch mode55npm run test:watch5657# Run tests with coverage58npm run test:coverage5960# Run a single test file with coverage61npm test -- --coverage --collectCoverageFrom='src/path/to/source.ts' path/to/__tests__/source.test.ts62```6364## File Naming and Location6566Test files follow one of two patterns:67681. **Dedicated `__tests__` directory** (preferred for components and modules):69 ```70 src/components/core/my-component/71 ├── my-component.tsx72 └── __tests__/73 └── my-component.test.tsx74 ```75762. **Co-located test file** (acceptable for utilities and simple modules):77 ```78 src/utils/79 ├── myUtil.ts80 └── myUtil.test.ts81 ```8283Naming convention: `ComponentName.test.tsx` for components, `hook-name.test.ts` for hooks, `util-name.test.ts` for utilities.8485**Do NOT use `.spec.tsx`** -- while technically matched, the project convention is `.test.tsx`.8687## Test Structure Template8889```tsx90import { render, screen } from "@testing-library/react";91import userEvent from "@testing-library/user-event";92import MyComponent from "../MyComponent";9394// Mock dependencies (use jest.mock, NOT vi.mock)95jest.mock("@/controllers/API/api", () => ({96 get: jest.fn(),97 post: jest.fn(),98}));99100describe("MyComponent", () => {101 beforeEach(() => {102 jest.clearAllMocks();103 });104105 describe("rendering", () => {106 it("should render the component with default props", () => {107 // Arrange108 render(<MyComponent />);109110 // Act - (none for render test)111112 // Assert113 expect(screen.getByRole("button", { name: /submit/i })).toBeInTheDocument();114 });115 });116117 describe("user interactions", () => {118 it("should call onSubmit when the form is submitted", async () => {119 // Arrange120 const user = userEvent.setup();121 const onSubmit = jest.fn();122 render(<MyComponent onSubmit={onSubmit} />);123124 // Act125 await user.click(screen.getByRole("button", { name: /submit/i }));126127 // Assert128 expect(onSubmit).toHaveBeenCalledTimes(1);129 });130 });131});132```133134## Incremental Testing Workflow135136When testing a directory with multiple files, follow this order:1371381. **Identify all source files** in the target directory1392. **Order by complexity** (simplest first):140 - Pure utility functions (no React, no side effects)141 - Constants and configuration objects142 - Custom hooks (no UI rendering)143 - Simple presentational components (no state, no side effects)144 - Stateful components with local state145 - Components using Zustand stores146 - Components with API calls or complex async behavior147 - Integration-level components that compose many children1483. **For each file**:149 a. Read the source file completely150 b. Identify all exported functions, components, and types151 c. Write tests covering all branches and edge cases152 d. Run the tests and fix any failures153 e. Check coverage and add tests for uncovered lines154 f. Move to the next file1554. **Run full directory coverage** at the end to verify156157## Complexity-Based Test Ordering158159Within a single test file, order test cases from simplest to most complex:1601611. Default rendering / initial state1622. Props variations and conditional rendering1633. User interactions (clicks, typing, form submission)1644. Async operations (API calls, timers)1655. Error states and edge cases1666. Integration with stores or context1677. Cleanup and unmount behavior168169## Core Principles170171### Arrange-Act-Assert (AAA)172Every test should have a clear three-phase structure. Use blank lines to separate each phase for readability.173174### Black-Box Testing175Test the component from the user's perspective. Query by role, label, text, or `data-testid` -- never by CSS class, internal state variable, or implementation detail.176177### Single Behavior Per Test178Each `it()` block should verify exactly one behavior. If you need to write "and" in the test name, split it into two tests.179180### Semantic Test Names181Use descriptive names that explain the expected behavior:182- Good: `"should disable the submit button when the form is invalid"`183- Bad: `"button test"` or `"test 1"`184185Format: `"should [expected behavior] when [condition]"`186187## Required Test Scenarios188189For every component, cover at minimum:190191### Rendering192- Default render with no optional props193- Render with all optional props provided194- Conditional rendering branches (if/else in JSX)195196### Props and State197- Each prop variation that changes rendered output198- Default prop values199- State transitions triggered by user actions200201### User Interactions202- Click handlers203- Form input and submission204- Keyboard navigation (if applicable)205- Hover/focus states (if applicable)206207### Challenge Tests (MANDATORY — not optional)208209**Happy path tests alone are NOT enough.** They only confirm the code works when everything is perfect. Real bugs hide in the cracks. You MUST write tests that actively TRY TO BREAK the code:210211**Unexpected inputs:**212- `null`, `undefined`, `""`, `[]`, `{}`, `0`, `-1`, `NaN`, `Infinity`213- What happens when a required prop is missing?214- What happens when data from the API comes back with missing fields?215216**Boundary values:**217- Max length strings (paste 10,000 chars in an input)218- Exactly at the limit, one past the limit219- Zero items, one item, maximum items220- First page, last page, out-of-range page221222**Malformed data:**223- API returns `{ data: null }` instead of `{ data: [] }`224- JSON with extra unexpected fields225- Dates in wrong format, numbers as strings226227**Error states:**228- Network failure (API rejects with 500)229- Authentication expired mid-action (401)230- Resource not found (404)231- Permission denied (403)232- Timeout233234**What should NOT happen:**235- Verify that deleting a flow does NOT delete flows from other users236- Verify that a read-only user CANNOT trigger write mutations237- Verify that XSS payloads in user input are sanitized238239**Rapid/concurrent actions:**240- Double-click on submit button241- Rapid repeated API calls242- Unmount component while async operation is in flight243244**Write tests based on REQUIREMENTS, not on what the source code does.** This is how you catch bugs where the code diverges from expected behavior.245246**When a test fails:** first ask if the CODE is wrong, not the test. Do NOT silently change a failing assertion to match the current code without understanding WHY.247248### Async Behavior249- Loading states250- Success states251- Error states252- Timeout/retry behavior253254## Coverage Goals255256Per source file:257- **Function coverage**: 100%258- **Branch coverage**: > 95%259- **Line coverage**: > 95%260- **Statement coverage**: > 95%261262Run coverage for a specific file:263```bash264npm test -- --coverage --collectCoverageFrom='src/path/to/file.ts' src/path/to/__tests__/file.test.ts265```266267## Important Rules2682691. **Never use Vitest APIs**: Use `jest.fn()`, `jest.mock()`, `jest.spyOn()`, `jest.mocked()` -- never `vi.*` equivalents.2702. **Never mock base UI components** from `@/components/ui/` -- render them as-is.2713. **Check `jest.setup.js` before mocking**: Many modules are already globally mocked (darkStore, genericIconComponent, react-markdown, radix-form, etc.). Do not re-mock them.2724. **Use `@testing-library/user-event`** over `fireEvent` for user interactions.2735. **Wrap state updates in `act()`** when testing Zustand stores or React state changes.2746. **Clean up after each test**: Use `beforeEach(() => jest.clearAllMocks())` and `afterEach` for timers.2757. **Always write both happy path AND adversarial tests** (null, undefined, empty values, boundary conditions, error states).2768. **Minimum coverage: 75%** (target 80%). Below 75% the task is not complete.277278## Forbidden Test Anti-Patterns279280| Pattern | Problem | How to Detect |281|---------|---------|---------------|282| **The Liar** | Test passes but doesn't verify the behavior it claims to test | Assertions don't match the test name |283| **The Mirror** | Test reads source code and asserts exactly what the code does — finds zero bugs | Test would never fail even if logic changes |284| **The Giant** | 50+ lines of setup, multiple acts, dozens of assertions | Should be 5+ separate tests |285| **The Mockery** | So many mocks that the test only tests the mock setup | Count mocks — if > 3 deep, rethink |286| **The Inspector** | Coupled to implementation details, breaks on any refactor | Tests internal state instead of behavior |287| **The Chain Gang** | Tests depend on execution order or share mutable state | Tests fail when run in isolation |288| **The Flaky** | Sometimes passes, sometimes fails with no code changes | Non-deterministic assertions or timing issues |289290## References291292- [Incremental Testing Workflow](references/workflow.md) - Step-by-step process for testing directories293- [Mocking Guide](references/mocking.md) - Patterns for mocking APIs, stores, routers, and context294- [Async Testing](references/async-testing.md) - Patterns for async operations, timers, and waitFor295- [Common Patterns](references/common-patterns.md) - Query priority, events, forms, modals, data-driven tests296- [Test Checklist](references/checklist.md) - Pre-submission verification checklist297- [Domain Components](references/domain-components.md) - Langflow-specific component testing patterns298- [Component Template](assets/component-test.template.tsx) - Starter template for component tests299- [Hook Template](assets/hook-test.template.ts) - Starter template for hook tests300- [Utility Template](assets/utility-test.template.ts) - Starter template for utility tests