cmms/frontend/src/components/workorders/__tests__
Jason Fraser 1ea6cf49ad Initial commit: contract management frontend built 2025-08-13 23:45:28 -04:00
..
AudioRecorder.test.js Initial commit: contract management frontend built 2025-08-13 23:45:28 -04:00
CostTracker.test.js Initial commit: contract management frontend built 2025-08-13 23:45:28 -04:00
PartsManager.test.js Initial commit: contract management frontend built 2025-08-13 23:45:28 -04:00
README.md Initial commit: contract management frontend built 2025-08-13 23:45:28 -04:00
TaskManager.test.js Initial commit: contract management frontend built 2025-08-13 23:45:28 -04:00
TimeTracker.test.js Initial commit: contract management frontend built 2025-08-13 23:45:28 -04:00
setup.js Initial commit: contract management frontend built 2025-08-13 23:45:28 -04:00

README.md

Work Order Component Tests

This directory contains comprehensive test suites for all critical work order components, implementing Test-Driven Development (TDD) practices to prevent bugs and ensure reliability.

Overview

The test suite was created in response to timer bugs found during manual testing. By implementing TDD, we ensure that:

  1. Critical bugs are caught early - Tests would have caught the timer duration calculation bugs
  2. Regressions are prevented - Existing functionality is protected by tests
  3. Code quality is maintained - Tests enforce proper component behavior
  4. Development is accelerated - Tests provide immediate feedback during development

Test Files

TimeTracker.test.js

Tests for the labor time tracking component that would have prevented the original timer bugs:

Key Test Categories:

  • Timer Functionality - Start/stop timer, elapsed time calculation, duration formatting
  • Manual Entry - Form validation, entry creation, data validation
  • Entry Editing - Edit mode, save/cancel functionality
  • Cost Calculations - Total hours, total cost calculations
  • Edge Cases - Disabled state, cleanup, invalid inputs

Critical Bug Prevention:

// This test would have caught the original 36-second minimum bug
it('should prevent timer bugs with minimum duration', async () => {
  // 1 second timer should not round to 36 seconds
  expect(entry.duration).toBeCloseTo(1 / 3600, 4) // 1 second, not 0.01 hours
  expect(entry.duration).toBeLessThan(0.01) // Should not be rounded to 36 seconds
})

PartsManager.test.js

Tests for parts assignment and inventory integration:

Key Test Categories:

  • Part Search and Selection - Search functionality, part addition, validation
  • Stock Checking - Availability verification, low stock warnings, out-of-stock handling
  • Cost Calculations - Unit prices, total costs, price overrides
  • Part Management - Remove parts, update quantities, validation
  • Data Validation - Input validation, model updates, external changes

CostTracker.test.js

Tests for cost tracking and budget management:

Key Test Categories:

  • Cost Calculations - Materials cost, labor cost, total cost calculations
  • Budget Management - Budget tracking, overrun detection, remaining calculation
  • Cost Breakdown - Percentage calculations, detailed breakdowns
  • Budget Alerts - Warning thresholds, alert messages, status indicators
  • Data Validation - Input validation, formatting, persistence

TaskManager.test.js

Tests for task/checklist functionality:

Key Test Categories:

  • Task Display - Progress calculation, completion tracking, duration formatting
  • Task Creation - Form validation, task addition, ID assignment
  • Task Completion - Toggle completion, batch operations, required task validation
  • Task Ordering - Drag and drop, reordering, index management
  • Templates - Load templates, save templates, clear operations

Test Infrastructure

setup.js

Global test configuration and utilities:

Features:

  • Mock configurations for UI components
  • Global mock functions for common dependencies
  • Custom test utilities and factories
  • Custom matchers for domain-specific assertions
  • Environment setup for consistent testing

Mock Factories:

global.createMockUser()      // Create test user data
global.createMockWorkOrder() // Create test work order data
global.createMockPart()      // Create test part data
global.createMockTask()      // Create test task data
global.createMockTimeEntry() // Create test time entry data

Custom Matchers:

expect(workOrder).toBeValidWorkOrder()     // Validate work order structure
expect(timeEntry).toBeValidTimeEntry()     // Validate time entry structure
expect(value).toBeCloseTo(expected, 2)     // Precise decimal comparison

vitest.config.js

Comprehensive Vitest configuration:

Features:

  • Vue component testing with jsdom environment
  • Code coverage reporting with thresholds
  • Path aliases for clean imports
  • Parallel test execution
  • HTML and verbose reporting

Coverage Thresholds:

global: {
  branches: 80%, functions: 80%, lines: 80%, statements: 80%
}

// Higher thresholds for critical components
TimeTracker.vue: { all: 90% }
CostTracker.vue: { all: 85% }

Running Tests

Basic Commands

# Run all tests
npm run test

# Run tests with UI
npm run test:ui

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

# Run with coverage report
npm run test:coverage

# Watch mode for development
npm run test:watch

Work Order Specific Commands

# Run only work order tests
npm run test:workorders

# Watch work order tests during development
npm run test:workorders:watch

# Run specific component tests
npx vitest src/components/workorders/__tests__/TimeTracker.test.js

Coverage Reports

# Generate coverage report
npm run test:coverage

# View HTML coverage report
open coverage/index.html

Test Patterns and Best Practices

1. Test Structure (AAA Pattern)

it('should calculate total cost correctly', async () => {
  // Arrange - Set up test data
  wrapper.vm.assignedParts = [mockPart1, mockPart2]
  
  // Act - Perform the action being tested
  const totalCost = wrapper.vm.totalCost
  
  // Assert - Verify the expected outcome
  expect(totalCost).toBeCloseTo(121.97, 2)
})

2. Edge Case Testing

it('should handle invalid duration inputs', () => {
  // Test edge cases that could cause bugs
  expect(wrapper.vm.formatDuration(Infinity)).toBe('0:00:00')
  expect(wrapper.vm.formatDuration('invalid')).toBe('0:00:00')
  expect(wrapper.vm.formatDuration(undefined)).toBe('0:00:00')
})

3. Integration Testing

it('should handle complete workflow from search to assignment', async () => {
  // Test full user workflows, not just individual functions
  // 1. Search for parts
  // 2. Select part
  // 3. Check stock
  // 4. Add part
  // 5. Verify assignment
  // 6. Verify emission
})

4. Performance Testing

it('should handle large datasets efficiently', async () => {
  const start = performance.now()
  await wrapper.setProps({ parts: largeParts })
  const end = performance.now()
  
  expect(end - start).toBeLessThan(100) // Should complete in <100ms
})

How TDD Prevents Bugs

Original Timer Bugs That Would Have Been Caught

  1. Duration Calculation Bug

    // Original bug: Math.max(0.01, ...) forced 36-second minimum
    // Test that would have caught it:
    expect(entry.duration).toBeCloseTo(1 / 3600, 4) // 1 second, not 36
    
  2. Display vs Saved Mismatch

    // Test ensures display matches saved values:
    expect(displayedTime).toBeCloseTo(calculatedTime, 6)
    
  3. Missing Edit Functionality

    // Test enforces edit functionality exists:
    expect(wrapper.vm.editEntry).toBeDefined()
    expect(wrapper.vm.saveEditedEntry).toBeDefined()
    

TDD Development Workflow

  1. Write Test First - Define expected behavior
  2. Run Test (Fails) - Confirm test correctly identifies missing functionality
  3. Write Minimal Code - Implement just enough to pass the test
  4. Run Test (Passes) - Confirm implementation works
  5. Refactor - Improve code while keeping tests passing
  6. Repeat - Continue with next requirement

Benefits Achieved

  • Early Bug Detection - Issues caught during development, not after deployment
  • Regression Prevention - Existing functionality protected by comprehensive tests
  • Documentation - Tests serve as executable specifications
  • Confidence - Safe refactoring with immediate feedback
  • Quality - Enforced error handling and edge case coverage

Continuous Integration

Tests are designed to run in CI/CD pipelines with:

  • Fast execution - Parallel test running and optimized mocks
  • Reliable results - Deterministic tests with proper cleanup
  • Clear reporting - Detailed output for debugging failures
  • Coverage enforcement - Fails build if coverage drops below thresholds

Extending the Test Suite

When adding new components or features:

  1. Create test file first - ComponentName.test.js
  2. Use existing patterns - Follow established test structure
  3. Include edge cases - Test error conditions and boundary values
  4. Mock dependencies - Use setup.js utilities
  5. Test integrations - Verify component interactions
  6. Update coverage - Ensure new code meets coverage thresholds

This comprehensive test suite ensures the work order system is robust, reliable, and maintainable while preventing the types of bugs that were discovered during manual testing.