# Morni E-Commerce Platform - Testing Plan

**Version:** 1.0  
**Date:** January 15, 2026  
**Status:** Ready for Implementation

---

## Executive Summary

This document outlines a comprehensive testing strategy for the Morni e-commerce platform. The platform is a Next.js 15 application with TypeScript, Redux state management, NextAuth authentication, and Stripe payment integration.

**Current Status:**
- ✅ Testing infrastructure is configured (Vitest + React Testing Library)
- ✅ Test utilities and mocks are ready
- ✅ Sample tests demonstrate the setup
- ❌ No production tests exist yet
- 🐛 Known bug: `cartSlice.js` lines 23-32 (incrementQuantity/decrementQuantity reference wrong state)

---

## Testing Goals

### Primary Objectives
1. **Achieve 70% code coverage** within 6 weeks
2. **Prevent regressions** in critical user flows (auth, cart, checkout)
3. **Improve code quality** through test-driven refactoring
4. **Enable confident deployments** with automated test gates
5. **Document expected behavior** through test descriptions

### Success Metrics
- Unit test coverage: 80%
- Integration test coverage: 60%
- API route test coverage: 70%
- Component test coverage: 65%
- Critical path E2E coverage: 100%

---

## Testing Strategy

### Test Pyramid

```
         /\
        /E2E\         (5%) - Critical user journeys
       /------\
      /  Intg  \      (25%) - API routes, feature flows
     /----------\
    /    Unit    \    (70%) - Utils, hooks, reducers
   /--------------\
```

### Technology Stack
- **Test Runner:** Vitest
- **Component Testing:** React Testing Library
- **Mocking:** Vitest mocks + MSW (for API)
- **Coverage:** Vitest coverage (v8 provider)
- **E2E (Future):** Playwright

---

## Implementation Phases

## Phase 1: Foundation (Week 1) - COMPLETED ✅

### Tasks
- [x] Setup Vitest configuration
- [x] Create test utilities and custom render
- [x] Setup mocks (Next.js, NextAuth, API)
- [x] Add test scripts to package.json
- [x] Create example tests

### Deliverables
- `vitest.config.ts`
- `tests/setup.ts`
- `tests/test-utils.tsx`
- `tests/mocks/api.ts`
- `tests/mocks/nextAuth.ts`
- Sample tests for Redux, utils, and components

---

## Phase 2: Utility & Core Logic Testing (Week 1-2)

**Priority:** 🔴 **HIGH** - Foundation for all other tests

### 2.1 API Client Tests
**File:** `utils/apiClient.test.tsx`

**Coverage:**
- [x] `getApiClient()` - GET requests with/without params
- [x] `postApiClient()` - POST requests with JSON payload
- [ ] `postFormData()` - FormData uploads
- [ ] Error handling (network, 4xx, 5xx)
- [ ] Token refresh scenarios
- [ ] Request timeout handling

**Estimated Time:** 4 hours

---

### 2.2 Image Helper Tests
**File:** `utils/imageHelper.test.ts`

**Coverage:**
- [x] `getImageUrl()` - CDN URL generation
- [x] `getImageUrlWithFallback()` - Fallback logic
- [x] `isCDNUrl()` - URL validation
- [ ] Edge cases (null, undefined, malformed URLs)
- [ ] Performance with large image arrays

**Estimated Time:** 2 hours

---

### 2.3 Helper Functions Tests
**File:** `utils/helper.test.tsx`

**Coverage:**
- [ ] `getUserFromCookie()` - Parse user data from cookie
- [ ] `getUserSessionId()` - Session ID generation/retrieval
- [ ] Cookie expiry handling
- [ ] Malformed data handling

**Estimated Time:** 3 hours

---

### 2.4 Server API Client Tests
**File:** `utils/serverApiClient.test.ts`

**Coverage:**
- [ ] Server-side API calls
- [ ] Header forwarding
- [ ] Error handling
- [ ] Cache behavior

**Estimated Time:** 3 hours

---

## Phase 3: State Management Testing (Week 2)

**Priority:** 🔴 **HIGH** - Critical for cart functionality

### 3.1 Cart Slice Tests
**File:** `app/redux/cartSlice.test.js`

**Coverage:**
- [x] `addToCart()` - Add new item
- [x] `addToCart()` - Increment existing item
- [x] `removeItem()` - Remove from cart
- [x] `setCartItemCount()` - Update count
- [ ] **FIX BUG:** `incrementQuantity()` - Fix state.user → state.cart
- [ ] **FIX BUG:** `decrementQuantity()` - Fix state.user → state.cart
- [ ] Edge cases (empty cart, quantity limits)
- [ ] Multiple items in cart

**Estimated Time:** 4 hours (including bug fix)

**Action Required:** Fix bug before enabling skipped tests

---

### 3.2 Redux Store Tests
**File:** `app/redux/store.test.js`

**Coverage:**
- [ ] Store initialization
- [ ] State persistence
- [ ] Multiple action dispatch
- [ ] State selectors

**Estimated Time:** 2 hours

---

## Phase 4: Component Testing (Week 2-3)

**Priority:** 🟠 **MEDIUM-HIGH** - User-facing functionality

### 4.1 Authentication Components

#### LoginForm Tests
**File:** `app/components/auth/loginForm.test.tsx` (Started)

**Coverage:**
- [x] Render login form
- [x] Handle Google sign-in
- [ ] Email/password validation
- [ ] Successful login flow
- [ ] Error display (invalid credentials)
- [ ] Redirect after login
- [ ] Remember me functionality

**Estimated Time:** 4 hours

---

#### SignupForm Tests
**File:** `app/components/auth/signupForm.test.tsx`

**Coverage:**
- [ ] Render signup form
- [ ] Form validation (email format, password strength)
- [ ] Successful registration
- [ ] Duplicate email handling
- [ ] Terms & conditions checkbox
- [ ] OTP verification flow

**Estimated Time:** 5 hours

---

### 4.2 Header Component
**File:** `app/components/common/header.test.tsx`

**Coverage:**
- [ ] Render navigation links
- [ ] Cart badge count display
- [ ] User menu (authenticated/unauthenticated)
- [ ] Search box interaction
- [ ] Mobile menu toggle
- [ ] Active route highlighting

**Estimated Time:** 4 hours

---

### 4.3 Cart Components

#### MiniCart Tests
**File:** `app/components/common/mini-cart.test.tsx`

**Coverage:**
- [ ] Display cart items
- [ ] Update quantity
- [ ] Remove items
- [ ] Show total price
- [ ] Empty cart state
- [ ] Checkout button

**Estimated Time:** 4 hours

---

### 4.4 Form Components

#### FormInput Tests
**File:** `app/components/form/forms.test.tsx`

**Coverage:**
- [ ] Text input rendering
- [ ] Validation states (error, success)
- [ ] Disabled state
- [ ] Required field indicator
- [ ] Input masking (if applicable)

**Estimated Time:** 3 hours

---

#### CustomDropdown Tests
**File:** `app/components/form/CustomDropdown.test.tsx`

**Coverage:**
- [ ] Render dropdown
- [ ] Open/close menu
- [ ] Select option
- [ ] Search/filter options
- [ ] Keyboard navigation

**Estimated Time:** 3 hours

---

### 4.5 Product Components

#### ProductCard Tests
**File:** `app/components/cards/product-card.test.tsx`

**Coverage:**
- [ ] Display product details
- [ ] Add to cart button
- [ ] Wishlist toggle
- [ ] Image loading states
- [ ] Price formatting
- [ ] Out of stock state

**Estimated Time:** 4 hours

---

## Phase 5: Custom Hooks Testing (Week 3)

**Priority:** 🟠 **MEDIUM** - Reusable logic

### 5.1 withAuth HOC Tests
**File:** `app/hook/withAuth.test.tsx`

**Coverage:**
- [ ] Redirect unauthenticated users
- [ ] Allow authenticated users
- [ ] Loading state display
- [ ] Redirect URL preservation

**Estimated Time:** 3 hours

---

### 5.2 useBreakpoint Tests
**File:** `app/components/useBreakpoint.test.tsx`

**Coverage:**
- [ ] Detect mobile breakpoint
- [ ] Detect tablet breakpoint
- [ ] Detect desktop breakpoint
- [ ] Handle window resize

**Estimated Time:** 2 hours

---

## Phase 6: API Route Testing (Week 3-4)

**Priority:** 🔴 **HIGH** - Backend logic validation

### 6.1 Products API
**File:** `app/api/products/route.test.ts`

**Coverage:**
- [ ] GET products with filters
- [ ] Query parameter parsing
- [ ] Sorting functionality
- [ ] Pagination
- [ ] Error handling (500, 404)
- [ ] Cache headers

**Estimated Time:** 5 hours

---

### 6.2 Cart API Routes

#### Add to Cart
**File:** `app/api/cart/add/route.test.ts`

**Coverage:**
- [ ] Add valid product
- [ ] Require authentication
- [ ] Handle duplicate items
- [ ] Validate product ID
- [ ] Return updated cart

**Estimated Time:** 3 hours

---

#### List Cart
**File:** `app/api/cart/list/route.test.ts`

**Coverage:**
- [ ] Return user's cart items
- [ ] Calculate totals
- [ ] Handle empty cart
- [ ] Include product details

**Estimated Time:** 2 hours

---

#### Remove from Cart
**File:** `app/api/cart/remove/route.test.ts`

**Coverage:**
- [ ] Remove existing item
- [ ] Handle non-existent item
- [ ] Require authentication
- [ ] Return updated cart

**Estimated Time:** 2 hours

---

#### Update Cart
**File:** `app/api/cart/update/route.test.ts`

**Coverage:**
- [ ] Update item quantity
- [ ] Validate quantity (min/max)
- [ ] Handle invalid item ID
- [ ] Return updated cart

**Estimated Time:** 3 hours

---

### 6.3 Authentication API Routes

#### Login
**File:** `app/api/auth/login/route.test.ts`

**Coverage:**
- [ ] Successful login with valid credentials
- [ ] Failed login with invalid credentials
- [ ] Rate limiting
- [ ] Token generation
- [ ] Account lockout after failed attempts

**Estimated Time:** 4 hours

---

#### Register
**File:** `app/api/auth/register/route.test.ts`

**Coverage:**
- [ ] Successful registration
- [ ] Duplicate email prevention
- [ ] Password validation
- [ ] Email verification trigger
- [ ] Input sanitization

**Estimated Time:** 4 hours

---

#### OTP Verification
**File:** `app/api/auth/otp-verify/route.test.ts`

**Coverage:**
- [ ] Valid OTP verification
- [ ] Expired OTP handling
- [ ] Invalid OTP handling
- [ ] Rate limiting

**Estimated Time:** 3 hours

---

### 6.4 Checkout & Order APIs

#### Checkout
**File:** `app/api/checkout/route.test.ts`

**Coverage:**
- [ ] Create checkout session
- [ ] Validate cart items
- [ ] Apply coupon codes
- [ ] Calculate shipping
- [ ] Stripe integration mock

**Estimated Time:** 6 hours

---

#### Order Creation
**File:** `app/api/order/route.test.ts`

**Coverage:**
- [ ] Create order after payment
- [ ] Order validation
- [ ] Inventory update
- [ ] Email notification trigger
- [ ] Error rollback

**Estimated Time:** 5 hours

---

### 6.5 Co-Creation API
**File:** `app/api/co-creation/route.test.ts`

**Coverage:**
- [ ] Submit co-creation request
- [ ] File upload handling
- [ ] Form validation
- [ ] Save draft functionality
- [ ] Retrieve user submissions

**Estimated Time:** 5 hours

---

## Phase 7: Integration Testing (Week 4-5)

**Priority:** 🟠 **MEDIUM** - End-to-end feature flows

### 7.1 Authentication Flow
**File:** `tests/integration/auth-flow.test.tsx`

**Coverage:**
- [ ] Complete signup → OTP → Login flow
- [ ] Google OAuth flow
- [ ] Password reset flow
- [ ] Session persistence

**Estimated Time:** 6 hours

---

### 7.2 Shopping Flow
**File:** `tests/integration/shopping-flow.test.tsx`

**Coverage:**
- [ ] Browse products → Add to cart → Update quantity → Checkout
- [ ] Apply filters and sorting
- [ ] Wishlist management
- [ ] Guest vs. authenticated user experience

**Estimated Time:** 8 hours

---

### 7.3 Co-Creation Flow
**File:** `tests/integration/co-creation-flow.test.tsx`

**Coverage:**
- [ ] Start co-creation → Upload images → Submit → Thank you
- [ ] Save draft and resume
- [ ] Validation at each step

**Estimated Time:** 6 hours

---

## Phase 8: Page Testing (Week 5)

**Priority:** 🟡 **LOW-MEDIUM** - Full page rendering

### 8.1 Homepage Tests
**File:** `app/page.test.tsx`

**Coverage:**
- [ ] Render all sections
- [ ] Hero video autoplay
- [ ] Product swiper functionality
- [ ] Instagram feed loading

**Estimated Time:** 3 hours

---

### 8.2 Product Listing Page
**File:** `app/category/page.test.tsx`

**Coverage:**
- [ ] Render product grid
- [ ] Filter sidebar
- [ ] Pagination
- [ ] Loading states

**Estimated Time:** 4 hours

---

### 8.3 Shopping Bag Page
**File:** `app/bag/page.test.tsx`

**Coverage:**
- [ ] Display cart items
- [ ] Update quantities
- [ ] Remove items
- [ ] Calculate totals
- [ ] Proceed to checkout

**Estimated Time:** 4 hours

---

## Phase 9: E2E Testing (Week 6) - Optional

**Priority:** 🟢 **LOW** - Nice to have

### Setup Playwright
- [ ] Install Playwright
- [ ] Configure test environment
- [ ] Setup test data seeding

### Critical User Journeys
1. **Complete Purchase Flow** (20 min)
   - Register → Browse → Add to cart → Checkout → Payment
   
2. **Co-Creation Submission** (15 min)
   - Login → Start co-creation → Upload → Submit

3. **Account Management** (10 min)
   - Login → Update profile → Change password

**Estimated Time:** 40 hours (full E2E suite)

---

## Test Coverage Targets

### By Module

| Module | Target Coverage | Priority |
|--------|----------------|----------|
| Utils | 85% | 🔴 High |
| API Routes | 75% | 🔴 High |
| Redux | 90% | 🔴 High |
| Components | 70% | 🟠 Medium |
| Pages | 50% | 🟡 Low |
| Hooks | 80% | 🟠 Medium |

### By Test Type

| Test Type | Count Target | Current |
|-----------|-------------|---------|
| Unit Tests | 150+ | 4 ✅ |
| Component Tests | 80+ | 1 ✅ |
| Integration Tests | 30+ | 0 |
| E2E Tests | 10+ | 0 |

---

## Known Issues & Bugs

### 🐛 Critical Bugs
1. **cartSlice.js** (Lines 23-32)
   - `incrementQuantity` and `decrementQuantity` reference `state.user` instead of `state.cart`
   - **Impact:** Functions don't work at all
   - **Fix:** Change `state.user` → `state.cart`
   - **Tests:** Currently skipped, will enable after fix

### ⚠️ Code Quality Issues
1. Mixed JS/TS files (Redux in .js)
2. Inconsistent error handling in API clients
3. No input validation in some form components
4. Missing loading states in several components

---

## Testing Best Practices

### General Guidelines
1. **Arrange-Act-Assert** pattern for all tests
2. **Test behavior, not implementation**
3. **Mock external dependencies** (APIs, third-party services)
4. **Use descriptive test names** (what, condition, expected)
5. **Keep tests isolated** (no shared state)

### Component Testing
```typescript
describe('ComponentName', () => {
  it('should [expected behavior] when [condition]', () => {
    // Arrange: Setup component and mocks
    // Act: Trigger user interaction
    // Assert: Verify expected outcome
  });
});
```

### API Route Testing
```typescript
describe('POST /api/endpoint', () => {
  it('should return 200 with valid data', async () => {
    // Arrange: Mock dependencies
    // Act: Call API route
    // Assert: Verify response
  });
});
```

### Async Testing
- Use `waitFor()` for async operations
- Use `findBy` queries for elements that appear later
- Mock timers when testing debounce/throttle

---

## CI/CD Integration

### GitHub Actions Workflow
```yaml
name: Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
      - run: npm install
      - run: npm run test:run
      - run: npm run test:coverage
```

### Pre-commit Hooks
- Run affected tests before commit
- Lint test files
- Check coverage thresholds

---

## Resource Requirements

### Time Estimates
- **Phase 1:** 8 hours (Complete ✅)
- **Phase 2:** 12 hours
- **Phase 3:** 6 hours
- **Phase 4:** 35 hours
- **Phase 5:** 5 hours
- **Phase 6:** 42 hours
- **Phase 7:** 20 hours
- **Phase 8:** 11 hours
- **Phase 9:** 40 hours (optional)

**Total:** ~180 hours (4-6 weeks with 1-2 developers)

### Team Structure
- **1 Senior Developer:** Test infrastructure, complex integration tests
- **1-2 Mid Developers:** Component tests, API route tests
- **QA Engineer (optional):** E2E tests, test plan validation

---

## Maintenance Plan

### Ongoing Activities
1. **Daily:** Run tests in CI/CD pipeline
2. **Weekly:** Review coverage reports, add tests for new features
3. **Monthly:** Refactor flaky tests, update test documentation
4. **Quarterly:** Review and update testing strategy

### Test Ownership
- Feature developers write unit/component tests
- QA team maintains integration/E2E tests
- Tech lead reviews test coverage in PRs

---

## Getting Started

### Run Tests
```bash
# Run all tests
npm run test

# Run with UI
npm run test:ui

# Run with coverage
npm run test:coverage

# Run specific test file
npm run test -- loginForm.test.tsx

# Run in watch mode
npm run test
```

### Writing Your First Test
1. Create test file next to source file (e.g., `utils.test.ts`)
2. Import test utilities: `import { describe, it, expect } from 'vitest'`
3. Write test following AAA pattern
4. Run test: `npm run test utils.test.ts`

### Sample Test Template
```typescript
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent } from '@tests/test-utils';

describe('ComponentName', () => {
  beforeEach(() => {
    // Setup
  });

  it('should render correctly', () => {
    render(<ComponentName />);
    expect(screen.getByText('Expected text')).toBeInTheDocument();
  });
});
```

---

## Next Steps

### Immediate Actions (This Week)
1. ✅ Review and approve this testing plan
2. ✅ Verify test infrastructure works (`npm run test`)
3. 🔲 **Fix cartSlice.js bug** (Lines 23-32)
4. 🔲 Start Phase 2: Utility testing
5. 🔲 Setup CI/CD pipeline with test runner

### Week 2 Priorities
1. Complete utility tests (Phase 2)
2. Fix Redux bug and complete cart tests (Phase 3)
3. Begin authentication component tests (Phase 4.1)

### Long-term Goals
1. Achieve 70% overall coverage (6 weeks)
2. Implement E2E tests for critical flows (8 weeks)
3. Establish test-first culture for new features
4. Automate regression testing in CI/CD

---

## Questions & Decisions Needed

1. **E2E Testing:** Do we implement Playwright E2E tests in Phase 9?
2. **Visual Regression:** Should we add visual regression testing (Percy/Chromatic)?
3. **Performance Testing:** Should we add Lighthouse CI for performance metrics?
4. **API Mocking:** Use MSW for API mocking or continue with fetch mocks?
5. **Coverage Enforcement:** Should we fail CI if coverage drops below threshold?

---

## Appendix

### Useful Commands
```bash
# Install dependencies
npm install

# Run tests in watch mode
npm run test

# Run tests once (CI mode)
npm run test:run

# Open Vitest UI
npm run test:ui

# Generate coverage report
npm run test:coverage

# Run specific test file
npm run test loginForm.test.tsx

# Run tests matching pattern
npm run test -- --grep="cart"

# Update snapshots
npm run test -- -u
```

### Resources
- [Vitest Documentation](https://vitest.dev/)
- [React Testing Library](https://testing-library.com/react)
- [Testing Best Practices](https://kentcdodds.com/blog/common-mistakes-with-react-testing-library)
- [Next.js Testing Guide](https://nextjs.org/docs/testing)

---

**Document Owner:** Development Team  
**Last Updated:** January 15, 2026  
**Next Review:** February 15, 2026
