> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Testing Infrastructure Improvements

> This document outlines improvements made to the testing infrastructure.

This document outlines improvements made to the testing infrastructure.

## Summary of Changes

### P0: Critical Fixes (Completed)

1. **✅ Fixed Playwright baseURL** - Changed from `http://localhost:8080` to `http://localhost:4173` to match the preview server
2. **✅ Created unified TestProviders wrapper** - New `tests/utils/providers.tsx` provides a single wrapper for all React hook tests
3. **✅ Added `test:e2e` / `test:e2e:ui` / `test:quick` scripts** - 2026-04-18
4. **✅ Repointed HR hook test imports to current subfolder paths** - 2026-04-18 (Phase 1 of dev/test stability plan)
5. **✅ Aliased Deno-only `npm:@sentry/deno` to a Node shim for Vitest** - 2026-04-18 (`tests/mocks/deno-sentry-shim.ts`)
6. **✅ TestProviders now wraps in MemoryRouter** with `noRouter` opt-out for tests that wrap their own router
7. **✅ Migrated 22+ failing component/hook tests to TestProviders + provider-wrapped renders** - 2026-04-18
8. **✅ Eliminated all `Failed Suites`** (`SKIP_SUPABASE_TESTS=true npm run test:unit` shows `0 failed`)

### P1: High Priority Improvements (Completed)

1. **✅ Module-specific cleanup utilities** - Split cleanup logic into `tests/utils/cleanup/`
2. **✅ Updated test templates** - `UNIT_TEST_TEMPLATE.ts` uses new TestProviders wrapper
3. **✅ Coverage thresholds raised** to 40% statements/lines/functions, 35% branches
4. **✅ Vitest pool switched to `threads` with bounded `maxWorkers`** - 2026-04-18 (`vitest.config.ts`)
5. **⏳ CI-safe test distinction** - documentation present; per-project split (`unit` / `integration` / `rls`) deferred until shared-mock cleanup audit completes (an `isolate: false` trial revealed \~200 cross-test contamination failures)
6. **⏳ Standardize test organization** - documentation present; in-flight

### P2: Medium Priority

1. **✅ Module-specific test scripts** - `test:e2e:{auth,hr,fa,ce,fw,gr,platform}`, `test:e2e:smoke`, `test:rls:smoke`, etc.
2. **⏳ Vitest projects split (unit/integration/rls)** - Deferred (see P1#5).
3. **⏳ Supabase types split by schema** - Tracked separately; the 100k-line generated types file is the dominant `tsc` cost.

***

## New Files Created

### Test Utilities

1. **`tests/utils/providers.tsx`**
   * Unified wrapper component with QueryClientProvider and OrganizationProvider
   * Replaces manual QueryClient setup in every test
   * Usage: `import { TestProviders, wrapper } from '@/tests/utils/providers';`

2. **`tests/utils/cleanup/`** directory
   * `pf-cleanup.ts` - Platform Foundation cleanup
   * `hr-cleanup.ts` - Human Resources cleanup
   * `fa-cleanup.ts` - Finance & Accounting cleanup
   * `fw-cleanup.ts` - Forms & Workflow cleanup
   * `index.ts` - Unified export for all cleanup functions

### Documentation

1. **`docs/testing/TESTING_IMPROVEMENTS.md`** (this file)
2. **`tests/utils/cleanup/README.md`** - Cleanup utilities documentation

***

## Manual Changes Required

Due to security hooks protecting certain configuration files, the following changes need to be made manually:

### 1. Add E2E Test Scripts to `package.json`

Add these scripts after `"test:rls"`:

```json theme={null}
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:quick": "vitest run tests/unit/ --changed",
```

### 2. Update `vitest.config.ts`

#### Enable Parallel Execution for Unit Tests

Change:

```typescript theme={null}
maxConcurrency: 1,
fileParallelism: false,
```

To:

```typescript theme={null}
// Enable parallel execution for unit tests (they don't need database)
maxConcurrency: process.env.CI ? 1 : 4, // Sequential in CI, parallel locally
fileParallelism: true, // Allow files to run in parallel
```

#### Increase Coverage Thresholds

Change:

```typescript theme={null}
thresholds: {
  statements: 20,
  branches: 15,
  functions: 20,
  lines: 20,
},
```

To:

```typescript theme={null}
thresholds: {
  statements: 40, // Increased from 20
  branches: 35,    // Increased from 15
  functions: 40,   // Increased from 20
  lines: 40,       // Increased from 20
},
```

#### Add Different Timeouts for Different Test Types

Consider adding test-specific timeouts:

```typescript theme={null}
testTimeout: 30000, // Keep for integration/RLS tests
// Unit tests can use shorter timeout via test.configure()
```

***

## Migration Guide

### For Existing Tests

#### 1. Update Hook Tests to Use TestProviders

**Before:**

```typescript theme={null}
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const createWrapper = () => {
  const queryClient = new QueryClient({ /* ... */ });
  return ({ children }) => (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
};

const { result } = renderHook(() => useMyHook(), { wrapper: createWrapper() });
```

**After:**

```typescript theme={null}
import { wrapper } from '@/tests/utils/providers';

const { result } = renderHook(() => useMyHook(), { wrapper });
```

#### 2. Update Component Tests to Use TestProviders

**Before:**

```typescript theme={null}
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();
render(
  <QueryClientProvider client={queryClient}>
    <MyComponent />
  </QueryClientProvider>
);
```

**After:**

```typescript theme={null}
import { TestProviders } from '@/tests/utils/providers';

render(
  <TestProviders>
    <MyComponent />
  </TestProviders>
);
```

#### 3. Update Cleanup in `tests/setup.ts`

**Before:**

```typescript theme={null}
// 894 lines of cleanup code in one file
```

**After:**

```typescript theme={null}
import { cleanupAllTestData } from '@/tests/utils/cleanup';

afterAll(async () => {
  if (isSupabaseConfigured) {
    await cleanupAllTestData(supabaseAdmin, testDataRegistry);
  }
});
```

***

## Test Organization Standards

### Naming Conventions

* **RLS Tests:** `{core}-{table}.rls.test.ts` (e.g., `hr-employees.rls.test.ts`)
* **Unit Tests:** `{core}/{feature}.test.ts` (e.g., `hr/useEmployees.test.ts`)
* **Integration Tests:** `{core}/{workflow}-workflow.test.ts` (e.g., `hr/onboarding-workflow.test.ts`)
* **E2E Tests:** `{core}/{feature}.spec.ts` (e.g., `hr/employee-management.spec.ts`)

### Directory Structure

```
tests/
  rls/              # All RLS tests (flat structure)
  unit/             # Unit tests organized by module
    {core}/
      {feature}.test.ts
  integration/     # Integration tests organized by module
    {core}/
      {workflow}-workflow.test.ts
  e2e/              # E2E tests organized by module
    {core}/
      {feature}.spec.ts
  utils/            # Test utilities
    providers.tsx   # Unified test providers
    cleanup/        # Module-specific cleanup
```

***

## Next Steps

1. **Manual Configuration Updates**
   * Update `package.json` with new test scripts
   * Update `vitest.config.ts` with parallel execution and higher coverage thresholds

2. **Migrate Existing Tests**
   * Update all hook tests to use `wrapper` from `@/tests/utils/providers`
   * Update component tests to use `TestProviders`
   * Refactor `tests/setup.ts` to use module-specific cleanup utilities

3. **Fix Failing Tests**
   * Address 155+ QueryClient provider failures
   * Fix 479 currently failing tests
   * Reduce 2,310 skipped tests (43% of suite)

4. **Documentation**
   * Update `docs/testing/index.md` with new patterns
   * Update `.cursor/agents/test-generator.md` to use new patterns
   * Create migration checklist for team

***

## Metrics to Track

| Metric             | Current   | Target           | Status                       |
| ------------------ | --------- | ---------------- | ---------------------------- |
| Skip rate          | 43%       | \<5%             | ⏳ In Progress                |
| Pass rate          | 84.5%     | >95%             | ⏳ In Progress                |
| Coverage threshold | 15-20%    | 40%              | ⏳ Pending Config Update      |
| Test duration      | 17 min    | \<10 min         | ⏳ Pending Parallel Execution |
| Setup file size    | 894 lines | \<200 lines/file | ✅ Completed                  |
| Failed tests       | 479       | \<50             | ⏳ In Progress                |

***

## References

* Testing Infrastructure Review Plan
* [Test Utilities README](../../tests/utils/README.md)
* [Cleanup Utilities README](../../tests/utils/cleanup/README.md)
* [Test Templates](../../specs/_templates/tests/)
