Test Frontend Units Skill
Use this skill to run unit tests for React components to validate that features are properly tested and components function as expected.
What This Skill Does
- Runs
npm test -- --run from the src/client/ui directory
- Executes Vitest test suite including:
src/components/CreateSurvey.test.tsx (15 tests - survey creation form)
src/components/GetSurvey.test.tsx (17 tests - survey fetching and display)
src/components/MySurveys.test.tsx (18 tests - user surveys listing)
- Tests run in jsdom environment simulating browser APIs
- Includes Auth0 authentication mocking and testing utilities
- Collects test results including:
- Total tests run, passed, failed, skipped
- Failed test names and error details
- Test execution time per file
- Reports failures with specific test names and assertion errors
- Exits with failure status if any tests fail
Test Framework & Environment
- Framework: Vitest v4.0.17
- Environment: jsdom (browser API simulation)
- Testing Library: @testing-library/react with @testing-library/user-event
- Auth Mocking: Auth0 useAuth0 hook mocked in test setup
- Utilities: Custom test utilities with render wrapper for consistent test setup
When to Use
- After implementing new React component features to ensure they're covered by tests
- Before deploying frontend changes to validate no regressions
- To check component functionality and user interactions
- After modifying existing components to ensure tests still pass
- To verify form handling, API integration, and state management
- During feature development to validate component behavior
How the Agent Should Use This Skill
- Prepare: Navigate to repository root
- Invoke: Run tests from repository root:
cd src/client/ui && npm test -- --run
- The `--run` flag executes tests once and exits (non-watch mode)
- Tests execute with jsdom environment for browser API simulation
3. **Parse Output**: Monitor stdout and stderr for:
- Test file summary (e.g., "Test Files 3 passed (3)")
- Test count summary (e.g., "Tests 50 passed (50)")
- Individual test execution times
- Failed test names and assertion errors
- Error details and stack traces if failures occur
4. **Handle Failures**: If any tests fail:
- Extract failed test names and file locations
- Review assertion errors or exception messages
- Report specific failures to user with context
- Halt further validation (don't proceed to Aspire/E2E)
5. **Report Success**: Include test count and execution time in report
## Success Criteria
- Exit code: 0
- All tests pass (output shows `failed: 0` or similar)
- No error output to stderr indicating test execution issues
- Output shows "Test Files X passed (X)" with all files passing
- Vitest runs and completes successfully
- Tests complete in reasonable time (under 5 seconds)
## Failure Indicators
- Exit code: 1 or non-zero
- Stdout contains failed test counts (e.g., `failed: 2`)
- Individual test failure messages with names and assertion details
- Console errors from test setup or mocking issues
- Timeout errors in async tests
- Import or type errors in test files
## Test Files & Components
### CreateSurvey.test.tsx
- **Component**: CreateSurvey (survey creation form)
- **Tests**: 15 test cases
- **Coverage**:
- Form rendering and input fields
- Adding/removing survey options
- Form validation and submission
- Error handling and success messages
- State management and form reset
- **Key Tests**:
- Renders form with correct fields
- Updates input values on user type
- Adds/removes options from survey
- Submits form with correct API payload
- Shows error/success messages
### GetSurvey.test.tsx
- **Component**: GetSurvey (survey fetching and display)
- **Tests**: 17 test cases
- **Coverage**:
- Survey fetching by ID
- Form submission for manual fetch
- Survey result display
- Error state handling (404, network errors)
- Loading indicators
- Component updates on prop changes
- **Key Tests**:
- Auto-fetches survey when ID prop changes
- Displays survey data and result breakdown
- Shows error messages for failed requests
- Handles 404 and network errors gracefully
- Updates input values on user interaction
### MySurveys.test.tsx
- **Component**: MySurveys (user surveys listing)
- **Tests**: 18 test cases
- **Coverage**:
- Fetching user's surveys
- Displaying surveys in table format
- Loading skeletons during fetch
- Empty state when no surveys exist
- Error handling and error messages
- User interactions (clicking buttons, rapid clicks)
- Multiple successive fetches
- **Key Tests**:
- Renders survey list with correct data
- Shows loading skeleton while fetching
- Shows empty state when no surveys
- Handles API errors gracefully
- Fetches surveys when button clicked
## Common Test Patterns Used
```typescript
// Component rendering test
render(<ComponentName />);
expect(screen.getByRole("heading", { name: /title/i })).toBeInTheDocument();
// Form interaction test with userEvent
const input = screen.getByPlaceholderText("placeholder");
await user.type(input, "value");
expect(input).toHaveValue("value");
// Async API test with mock
const mockApiCall = vi.fn().mockResolvedValue({ok: true, json: async () => data});
vi.mocked(hooks.useApiCall).mockReturnValue({apiCall: mockApiCall});
await user.click(button);
await waitFor(() => expect(mockApiCall).toHaveBeenCalled());
// Error handling test
mockApiCall.mockRejectedValue(new Error("Network error"));
// ... trigger component action
await waitFor(() => expect(screen.getByText("Network error")).toBeInTheDocument());
Test Setup & Infrastructure
- vitest.config.ts: Configures jsdom environment, global APIs, setup files
- src/test/setup.ts: Auth0 useAuth0 hook mock, window.matchMedia mock
- src/test/test-utils.tsx: Custom render function with testing utilities wrapper
- Mock Data: Realistic survey and user data structures matching API types
Notes
- Tests are located in
src/client/ui/src/components/ directory
- All tests use jsdom for browser API simulation (window, document, etc.)
- Auth0 authentication is mocked so tests don't require real tokens
- Tests use userEvent for realistic user interaction simulation
- Custom hooks (useApiCall, useSurveyFetch) are mocked via vi.mocked()
- Tests include loading states, error states, and empty states
- Current test suite: 50 tests passing (100% success rate)
- Run with
npm test -- --ui for interactive Vitest UI dashboard
- Run with
npm test -- --coverage to generate coverage report
- Test execution time: ~1.5-2 seconds for full suite
Common Issues & Troubleshooting
| Issue |
Cause |
Solution |
| "Unable to find an element" error |
Selector doesn't match any elements |
Use more specific selectors (getByRole, getByLabelText) or use screen.debug() |
| Timeout in waitFor |
Async operation not completing |
Check mock setup, increase timeout, verify component updates state |
| Import errors in tests |
Wrong import paths |
Use relative paths from test file location (e.g., ../test/test-utils) |
| Type errors with mocks |
Mock return type mismatch |
Ensure mock data matches component prop types |
| Auth0 not mocked |
Setup.ts not loading |
Verify vitest.config.ts has correct setupFiles path |
Next Steps After Success
Once all frontend unit tests pass, typically invoke:
- Validate Aspire Runtime Skill - to start the full application environment
- Validate E2E Skill - to run end-to-end acceptance tests and verify features work in running application
Dependencies
Run these from src/client/ui directory once:
npm install
Installed packages:
vitest - test runner
@testing-library/react - component testing utilities
@testing-library/user-event - realistic user interaction simulation
@testing-library/jest-dom - custom matchers
@vitest/ui - interactive test dashboard
jsdom - browser environment simulation
References
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: test-frontend-units3description: Executes frontend component unit tests for the Fake Survey Generator React application using Vitest. This skill validates that React components are properly tested and that existing tests continue to pass. Reports test failures and code coverage metrics. Use when this capability is needed.4---56# Test Frontend Units Skill78Use this skill to run unit tests for React components to validate that features are properly tested and components function as expected.910## What This Skill Does11121. Runs `npm test -- --run` from the `src/client/ui` directory132. Executes Vitest test suite including:14 - `src/components/CreateSurvey.test.tsx` (15 tests - survey creation form)15 - `src/components/GetSurvey.test.tsx` (17 tests - survey fetching and display)16 - `src/components/MySurveys.test.tsx` (18 tests - user surveys listing)173. Tests run in jsdom environment simulating browser APIs184. Includes Auth0 authentication mocking and testing utilities195. Collects test results including:20 - Total tests run, passed, failed, skipped21 - Failed test names and error details22 - Test execution time per file236. Reports failures with specific test names and assertion errors247. Exits with failure status if any tests fail2526## Test Framework & Environment2728- **Framework**: Vitest v4.0.1729- **Environment**: jsdom (browser API simulation)30- **Testing Library**: @testing-library/react with @testing-library/user-event31- **Auth Mocking**: Auth0 useAuth0 hook mocked in test setup32- **Utilities**: Custom test utilities with render wrapper for consistent test setup3334## When to Use3536- After implementing new React component features to ensure they're covered by tests37- Before deploying frontend changes to validate no regressions38- To check component functionality and user interactions39- After modifying existing components to ensure tests still pass40- To verify form handling, API integration, and state management41- During feature development to validate component behavior4243## How the Agent Should Use This Skill44451. **Prepare**: Navigate to repository root462. **Invoke**: Run tests from repository root:47 ```48 cd src/client/ui && npm test -- --run49 ```50 - The `--run` flag executes tests once and exits (non-watch mode)51 - Tests execute with jsdom environment for browser API simulation523. **Parse Output**: Monitor stdout and stderr for:53 - Test file summary (e.g., "Test Files 3 passed (3)")54 - Test count summary (e.g., "Tests 50 passed (50)")55 - Individual test execution times56 - Failed test names and assertion errors57 - Error details and stack traces if failures occur584. **Handle Failures**: If any tests fail:59 - Extract failed test names and file locations60 - Review assertion errors or exception messages61 - Report specific failures to user with context62 - Halt further validation (don't proceed to Aspire/E2E)635. **Report Success**: Include test count and execution time in report6465## Success Criteria6667- Exit code: 068- All tests pass (output shows `failed: 0` or similar)69- No error output to stderr indicating test execution issues70- Output shows "Test Files X passed (X)" with all files passing71- Vitest runs and completes successfully72- Tests complete in reasonable time (under 5 seconds)7374## Failure Indicators7576- Exit code: 1 or non-zero77- Stdout contains failed test counts (e.g., `failed: 2`)78- Individual test failure messages with names and assertion details79- Console errors from test setup or mocking issues80- Timeout errors in async tests81- Import or type errors in test files8283## Test Files & Components8485### CreateSurvey.test.tsx86- **Component**: CreateSurvey (survey creation form)87- **Tests**: 15 test cases88- **Coverage**:89 - Form rendering and input fields90 - Adding/removing survey options91 - Form validation and submission92 - Error handling and success messages93 - State management and form reset94- **Key Tests**:95 - Renders form with correct fields96 - Updates input values on user type97 - Adds/removes options from survey98 - Submits form with correct API payload99 - Shows error/success messages100101### GetSurvey.test.tsx102- **Component**: GetSurvey (survey fetching and display)103- **Tests**: 17 test cases104- **Coverage**:105 - Survey fetching by ID106 - Form submission for manual fetch107 - Survey result display108 - Error state handling (404, network errors)109 - Loading indicators110 - Component updates on prop changes111- **Key Tests**:112 - Auto-fetches survey when ID prop changes113 - Displays survey data and result breakdown114 - Shows error messages for failed requests115 - Handles 404 and network errors gracefully116 - Updates input values on user interaction117118### MySurveys.test.tsx119- **Component**: MySurveys (user surveys listing)120- **Tests**: 18 test cases121- **Coverage**:122 - Fetching user's surveys123 - Displaying surveys in table format124 - Loading skeletons during fetch125 - Empty state when no surveys exist126 - Error handling and error messages127 - User interactions (clicking buttons, rapid clicks)128 - Multiple successive fetches129- **Key Tests**:130 - Renders survey list with correct data131 - Shows loading skeleton while fetching132 - Shows empty state when no surveys133 - Handles API errors gracefully134 - Fetches surveys when button clicked135136## Common Test Patterns Used137138```typescript139// Component rendering test140render(<ComponentName />);141expect(screen.getByRole("heading", { name: /title/i })).toBeInTheDocument();142143// Form interaction test with userEvent144const input = screen.getByPlaceholderText("placeholder");145await user.type(input, "value");146expect(input).toHaveValue("value");147148// Async API test with mock149const mockApiCall = vi.fn().mockResolvedValue({ok: true, json: async () => data});150vi.mocked(hooks.useApiCall).mockReturnValue({apiCall: mockApiCall});151await user.click(button);152await waitFor(() => expect(mockApiCall).toHaveBeenCalled());153154// Error handling test155mockApiCall.mockRejectedValue(new Error("Network error"));156// ... trigger component action157await waitFor(() => expect(screen.getByText("Network error")).toBeInTheDocument());158```159160## Test Setup & Infrastructure161162- **vitest.config.ts**: Configures jsdom environment, global APIs, setup files163- **src/test/setup.ts**: Auth0 useAuth0 hook mock, window.matchMedia mock164- **src/test/test-utils.tsx**: Custom render function with testing utilities wrapper165- **Mock Data**: Realistic survey and user data structures matching API types166167## Notes168169- Tests are located in `src/client/ui/src/components/` directory170- All tests use jsdom for browser API simulation (window, document, etc.)171- Auth0 authentication is mocked so tests don't require real tokens172- Tests use userEvent for realistic user interaction simulation173- Custom hooks (useApiCall, useSurveyFetch) are mocked via vi.mocked()174- Tests include loading states, error states, and empty states175- Current test suite: **50 tests passing** (100% success rate)176- Run with `npm test -- --ui` for interactive Vitest UI dashboard177- Run with `npm test -- --coverage` to generate coverage report178- Test execution time: ~1.5-2 seconds for full suite179180## Common Issues & Troubleshooting181182| Issue | Cause | Solution |183| --------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------- |184| "Unable to find an element" error | Selector doesn't match any elements | Use more specific selectors (getByRole, getByLabelText) or use screen.debug() |185| Timeout in waitFor | Async operation not completing | Check mock setup, increase timeout, verify component updates state |186| Import errors in tests | Wrong import paths | Use relative paths from test file location (e.g., `../test/test-utils`) |187| Type errors with mocks | Mock return type mismatch | Ensure mock data matches component prop types |188| Auth0 not mocked | Setup.ts not loading | Verify vitest.config.ts has correct setupFiles path |189190## Next Steps After Success191192Once all frontend unit tests pass, typically invoke:193- **Validate Aspire Runtime Skill** - to start the full application environment194- **Validate E2E Skill** - to run end-to-end acceptance tests and verify features work in running application195196## Dependencies197198Run these from `src/client/ui` directory once:199```bash200npm install201```202203Installed packages:204- `vitest` - test runner205- `@testing-library/react` - component testing utilities206- `@testing-library/user-event` - realistic user interaction simulation207- `@testing-library/jest-dom` - custom matchers208- `@vitest/ui` - interactive test dashboard209- `jsdom` - browser environment simulation210211## References212213- Test files: `src/client/ui/src/components/*.test.tsx`214- Vitest docs: https://vitest.dev/215- Testing Library docs: https://testing-library.com/docs/react-testing-library/intro216- Test utilities: `src/client/ui/src/test/`217218---219> Converted and distributed by [TomeVault](https://tomevault.io/claim/marcelmichau) — claim your Tome and manage your conversions.220<!-- tomevault:4.0:skill_md:2026-04-11 -->