Eve library

Mock Services Documentation

Other

Revision 1

On this page

This directory contains mock implementations of critical services for testing purposes.

Purpose#

Mocks provide:

  • Predictable behavior for unit testing
  • Isolation from external dependencies (audio hardware, network, etc.)
  • Faster test execution without real API calls
  • Controlled simulation of edge cases and errors

Available Mocks#

Mock Real Service Purpose
SpeechRecognitionService Voice input Simulates speech-to-text with controlled results
VoiceResponseService TTS output Simulates text-to-speech synthesis
WebRTCService Real-time comm Simulates WebRTC connections and streams
BargeInService Voice detection Simulates voice activity detection
BluetoothAudioService BT devices Simulates Bluetooth device connections
AdvancedAudioProcessor Audio DSP Simulates audio effects processing
AdvancedSyncManager Data sync Simulates cross-device synchronization
DataSynchronizationService Generic sync Simulates data layer synchronization
EncryptionService Crypto Simulates encryption/decryption operations

Usage Patterns#

Automatic Jest Resolution#

Jest automatically resolves imports from __mocks__ when configured:

typescript
// jest.config.js
moduleNameMapper: {
  '../SpeechRecognitionService': '<rootDir>/services/__mocks__/SpeechRecognitionService.ts'
}

Manual Mock Import#

For explicit control in tests:

typescript
// Import mock before the module under test
jest.mock('../SpeechRecognitionService');
import { speechRecognitionService } from '../__mocks__/SpeechRecognitionService';

describe('MyComponent', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('handles speech input', async () => {
    await speechRecognitionService.startListening();
    expect(speechRecognitionService.startListening).toHaveBeenCalled();
  });
});

Event Simulation#

Mocks extend EventEmitter for realistic event handling:

typescript
// Test event handling
speechRecognitionService.on('partialResult', (result) => {
  expect(result.text).toBe('Hello world');
});

await speechRecognitionService.startListening();

State Control#

Mocks maintain internal state for realistic behavior:

typescript
// State-dependent behavior
await speechRecognitionService.initialize();
await speechRecognitionService.startListening(); // Works after init

// Without init, throws error
const uninitService = new SpeechRecognitionService();
await expect(uninitService.startListening()).rejects.toThrow('not initialized');

Error Simulation#

To test error handling, modify mock implementation:

typescript
beforeEach(() => {
  speechRecognitionService.startListening.mockRejectedValueOnce(
    new Error('Microphone access denied')
  );
});

it('handles permission errors', async () => {
  await expect(component.enableVoice()).rejects.toThrow('Microphone access denied');
});

Mock Implementation Guidelines#

When creating new mocks:

  1. Extend EventEmitter - For services that emit events
  2. Use jest.fn() - For all public methods to enable tracking
  3. Maintain state - Track initialization, active status
  4. Export singleton + class - Support both usage patterns
  5. Document behavior - Comment expected mock responses

Template#

typescript
/**
 * Mock for [ServiceName] - [brief description]
 */
import { EventEmitter } from 'events';

const MockServiceName = class extends EventEmitter {
  private isInitialized = false;

  initialize = jest.fn().mockImplementation(async () => {
    this.isInitialized = true;
  });

  someMethod = jest.fn().mockResolvedValue({ success: true });

  destroy = jest.fn().mockImplementation(async () => {
    this.isInitialized = false;
    this.removeAllListeners();
  });
};

const mockServiceInstance = new MockServiceName();

jest.mock('../ServiceName', () => ({
  serviceName: mockServiceInstance,
  ServiceName: MockServiceName,
  __esModule: true,
}));

export const serviceName = mockServiceInstance;
export { MockServiceName as ServiceName };

Preload Configuration#

The preload-mocks.js file configures mock loading order and global setup for Jest. It's referenced in jest.setup.js.

Keeping Mocks Updated#

When updating the real service:

  1. Update mock interface to match new methods
  2. Add appropriate mock return values
  3. Update state management if behavior changes
  4. Run tests to verify compatibility:
    bash
    npm test -- --testPathPattern="ServiceName"