Skip to content

Add comprehensive event tests for NodeAutocomplete component #152

Closed

Description

@malibio

Problem Statement

The NodeAutocomplete component has critical event handling logic that is completely untested. This modal component handles keyboard navigation, event propagation, and auto-focus behaviors - all prone to subtle bugs that only manual testing currently catches.

Specific Untested Code:

  • Lines 100-148: Keyboard event handling (ArrowUp/Down, Enter, Escape)
  • Lines 107, 113, 119, 126: stopPropagation() calls to prevent background interactions
  • Lines 143-148: Event listener setup and cleanup in onMount
  • Lines 56-85: Smart positioning logic for viewport edges
  • Lines 90-98: Scroll-to-selected behavior

Why This Matters

Production Risks:

  1. Background Actions - If stopPropagation() fails, pressing Enter might create a new node while also selecting from autocomplete
  2. Focus Traps - Users could get stuck in modal, unable to escape
  3. Memory Leaks - Event listeners on document persist after unmount
  4. Positioning Bugs - Modal could render off-screen or overlap trigger element
  5. Accessibility - Keyboard navigation crucial for accessibility could break silently

Current Reality:

  • Component has 150+ lines of event-critical code
  • Zero automated tests
  • Changes verified only by manual clicking
  • Regressions caught in production

Files Involved

Component Under Test:

  • src/lib/components/ui/node-autocomplete/node-autocomplete.svelte (all 216 lines)

Test File to Create:

  • src/tests/components/node-autocomplete.test.ts

Dependencies:

Reference Files:

  • src/tests/component/content-editable-controller.test.ts - Similar event testing patterns

Acceptance Criteria

Test Coverage Requirements

Must test all event scenarios:

  • Rendering Tests (3 tests)

    • Renders when visible=true
    • Hides when visible=false
    • Displays all results with correct node types
  • Keyboard Navigation (7 tests)

    • ArrowDown moves selection down
    • ArrowUp moves selection up
    • ArrowDown at bottom stays at bottom
    • ArrowUp at top stays at top
    • Enter selects current item
    • Escape closes modal
    • All keyboard events prevent default and stop propagation
  • Event Propagation (3 tests)

    • stopPropagation() called for ArrowUp/Down
    • stopPropagation() called for Enter
    • stopPropagation() called for Escape
    • Background elements don't receive events
  • Event Dispatching (3 tests)

    • Dispatches 'select' event with correct NodeResult
    • Dispatches 'close' event on Escape
    • Mouse click on item dispatches 'select'
  • Lifecycle Management (2 tests)

    • addEventListener called with 'keydown' on mount
    • removeEventListener called with same handler on unmount
  • Smart Positioning (4 tests)

    • Positions below cursor when space available
    • Positions above cursor when insufficient space below
    • Doesn't overflow viewport horizontally
    • Handles edge case: cursor near corner
  • Scroll Behavior (2 tests)

    • Scrolls selected item into view
    • Handles scrolling with smooth behavior
  • Edge Cases (3 tests)

    • Handles empty results array
    • Handles query changes resetting selection
    • Handles rapid keyboard events

Detailed Test Implementation

Core Test Structure

// src/tests/components/node-autocomplete.test.ts
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { screen, fireEvent, waitFor } from '@testing-library/svelte';
import NodeAutocomplete from '$lib/components/ui/node-autocomplete/node-autocomplete.svelte';
import { renderComponent, createUserEvents, waitForEffects } from './svelte-test-utils';
import type { NodeResult } from '$lib/components/ui/node-autocomplete';

describe('NodeAutocomplete Component', () => {
  const mockResults: NodeResult[] = [
    { id: 'node-1', title: 'First Node', type: 'text', subtitle: 'Text note', metadata: '2 days ago' },
    { id: 'node-2', title: 'Second Node', type: 'task', subtitle: 'Task item', metadata: '1 week ago' },
    { id: 'node-3', title: 'Third Node', type: 'document', subtitle: 'Doc', metadata: 'Today' }
  ];

  describe('Rendering', () => {
    it('should render when visible is true', () => {
      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 100, y: 200 }
      });

      expect(screen.getByRole('listbox')).toBeInTheDocument();
      expect(screen.getByLabelText('Node reference autocomplete')).toBeInTheDocument();
    });

    it('should not render when visible is false', () => {
      renderComponent(NodeAutocomplete, {
        visible: false,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
    });

    it('should display all results with node type icons', () => {
      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      expect(screen.getByText('First Node')).toBeInTheDocument();
      expect(screen.getByText('Second Node')).toBeInTheDocument();
      expect(screen.getByText('Third Node')).toBeInTheDocument();

      // Verify node type labels rendered
      expect(screen.getByText('Text')).toBeInTheDocument();
      expect(screen.getByText('Task')).toBeInTheDocument();
    });
  });

  describe('Keyboard Navigation', () => {
    it('should move selection down with ArrowDown', async () => {
      const user = createUserEvents();

      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      const items = screen.getAllByRole('option');

      // First item selected initially
      expect(items[0]).toHaveAttribute('aria-selected', 'true');
      expect(items[1]).toHaveAttribute('aria-selected', 'false');

      // Arrow down
      await user.keyboard('{ArrowDown}');
      await waitForEffects();

      // Second item now selected
      expect(items[0]).toHaveAttribute('aria-selected', 'false');
      expect(items[1]).toHaveAttribute('aria-selected', 'true');
    });

    it('should move selection up with ArrowUp', async () => {
      const user = createUserEvents();

      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      // Move to second item first
      await user.keyboard('{ArrowDown}');
      await waitForEffects();

      const items = screen.getAllByRole('option');
      expect(items[1]).toHaveAttribute('aria-selected', 'true');

      // Arrow up
      await user.keyboard('{ArrowUp}');
      await waitForEffects();

      // Back to first item
      expect(items[0]).toHaveAttribute('aria-selected', 'true');
      expect(items[1]).toHaveAttribute('aria-selected', 'false');
    });

    it('should stay at bottom when ArrowDown pressed at last item', async () => {
      const user = createUserEvents();

      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      // Move to last item
      await user.keyboard('{ArrowDown}{ArrowDown}');
      await waitForEffects();

      const items = screen.getAllByRole('option');
      expect(items[2]).toHaveAttribute('aria-selected', 'true');

      // Try to go down again
      await user.keyboard('{ArrowDown}');
      await waitForEffects();

      // Still at last item
      expect(items[2]).toHaveAttribute('aria-selected', 'true');
    });

    it('should stay at top when ArrowUp pressed at first item', async () => {
      const user = createUserEvents();

      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      const items = screen.getAllByRole('option');

      // Already at first item
      expect(items[0]).toHaveAttribute('aria-selected', 'true');

      // Try to go up
      await user.keyboard('{ArrowUp}');
      await waitForEffects();

      // Still at first item
      expect(items[0]).toHaveAttribute('aria-selected', 'true');
    });

    it('should select item with Enter key', async () => {
      const user = createUserEvents();
      const selectHandler = vi.fn();

      const { component } = renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      component.$on('select', selectHandler);

      // Press Enter (first item selected by default)
      await user.keyboard('{Enter}');
      await waitForEffects();

      expect(selectHandler).toHaveBeenCalledWith(
        expect.objectContaining({
          detail: mockResults[0]
        })
      );
    });

    it('should close modal with Escape key', async () => {
      const user = createUserEvents();
      const closeHandler = vi.fn();

      const { component } = renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      component.$on('close', closeHandler);

      await user.keyboard('{Escape}');
      await waitForEffects();

      expect(closeHandler).toHaveBeenCalled();
    });
  });

  describe('Event Propagation', () => {
    it('should prevent default and stop propagation for ArrowDown', async () => {
      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      const preventDefaultSpy = vi.fn();
      const stopPropagationSpy = vi.fn();

      const event = new KeyboardEvent('keydown', { key: 'ArrowDown' });
      Object.defineProperty(event, 'preventDefault', { value: preventDefaultSpy });
      Object.defineProperty(event, 'stopPropagation', { value: stopPropagationSpy });

      document.dispatchEvent(event);

      expect(preventDefaultSpy).toHaveBeenCalled();
      expect(stopPropagationSpy).toHaveBeenCalled();
    });

    it('should prevent background node creation when Enter pressed', async () => {
      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      const preventDefaultSpy = vi.fn();
      const stopPropagationSpy = vi.fn();

      const event = new KeyboardEvent('keydown', { key: 'Enter' });
      Object.defineProperty(event, 'preventDefault', { value: preventDefaultSpy });
      Object.defineProperty(event, 'stopPropagation', { value: stopPropagationSpy });

      document.dispatchEvent(event);

      // CRITICAL: These must be called to prevent background actions
      expect(preventDefaultSpy).toHaveBeenCalled();
      expect(stopPropagationSpy).toHaveBeenCalled();
    });

    it('should not handle events when not visible', async () => {
      const selectHandler = vi.fn();

      const { component } = renderComponent(NodeAutocomplete, {
        visible: false,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      component.$on('select', selectHandler);

      const event = new KeyboardEvent('keydown', { key: 'Enter' });
      document.dispatchEvent(event);

      expect(selectHandler).not.toHaveBeenCalled();
    });
  });

  describe('Lifecycle Management', () => {
    it('should add keydown listener on mount', () => {
      const addEventListenerSpy = vi.spyOn(document, 'addEventListener');

      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      expect(addEventListenerSpy).toHaveBeenCalledWith(
        'keydown',
        expect.any(Function)
      );
    });

    it('should remove keydown listener on unmount', () => {
      const addEventListenerSpy = vi.spyOn(document, 'addEventListener');
      const removeEventListenerSpy = vi.spyOn(document, 'removeEventListener');

      const { unmount } = renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      // Get the handler that was added
      const addedHandler = addEventListenerSpy.mock.calls[0][1];

      unmount();

      // Verify same handler was removed
      expect(removeEventListenerSpy).toHaveBeenCalledWith('keydown', addedHandler);
    });
  });

  describe('Smart Positioning', () => {
    beforeEach(() => {
      // Mock window dimensions
      Object.defineProperty(window, 'innerWidth', { value: 1024, writable: true });
      Object.defineProperty(window, 'innerHeight', { value: 768, writable: true });
    });

    it('should position below cursor when space available', () => {
      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 100, y: 100 } // Plenty of space below
      });

      const listbox = screen.getByRole('listbox');
      const style = listbox.style;

      expect(style.top).toBeDefined();
      expect(style.bottom).toBe('');
      expect(parseInt(style.top)).toBeGreaterThan(100); // Below cursor
    });

    it('should position above cursor when insufficient space below', () => {
      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 100, y: 700 } // Near bottom
      });

      const listbox = screen.getByRole('listbox');
      const style = listbox.style;

      expect(style.bottom).toBeDefined();
      expect(style.top).toBe('');
    });

    it('should not overflow viewport horizontally', () => {
      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 1000, y: 100 } // Near right edge
      });

      const listbox = screen.getByRole('listbox');
      const style = listbox.style;
      const left = parseInt(style.left);

      // Should be adjusted to fit within viewport
      expect(left + 360).toBeLessThanOrEqual(1024); // max-width is 360px
    });
  });

  describe('Edge Cases', () => {
    it('should handle empty results gracefully', () => {
      renderComponent(NodeAutocomplete, {
        visible: true,
        results: [],
        position: { x: 0, y: 0 }
      });

      expect(screen.getByRole('listbox')).toBeInTheDocument();
      expect(screen.queryByRole('option')).not.toBeInTheDocument();
    });

    it('should reset selection when results change', async () => {
      const { component } = renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      const user = createUserEvents();

      // Move to second item
      await user.keyboard('{ArrowDown}');
      await waitForEffects();

      let items = screen.getAllByRole('option');
      expect(items[1]).toHaveAttribute('aria-selected', 'true');

      // Change results
      const newResults = [mockResults[0]];
      component.$set({ results: newResults });
      await waitForEffects();

      // Selection should reset to first item
      items = screen.getAllByRole('option');
      expect(items[0]).toHaveAttribute('aria-selected', 'true');
    });

    it('should handle rapid keyboard events', async () => {
      const user = createUserEvents();

      renderComponent(NodeAutocomplete, {
        visible: true,
        results: mockResults,
        position: { x: 0, y: 0 }
      });

      // Rapid arrow presses
      await user.keyboard('{ArrowDown}{ArrowDown}{ArrowUp}{ArrowDown}');
      await waitForEffects();

      const items = screen.getAllByRole('option');
      // Should end up at second item
      expect(items[1]).toHaveAttribute('aria-selected', 'true');
    });
  });
});

Test Execution Requirements

All Tests Must Pass

bun run test -- node-autocomplete.test.ts

Coverage Requirements

  • Line coverage: >90% for node-autocomplete.svelte
  • Branch coverage: >85%
  • All event handlers covered

No Console Output

  • No errors
  • No warnings
  • No unhandled promise rejections

Dependencies

Requires (Must Complete First):

Blocks:

Definition of Done

  • All 27 test cases implemented and passing
  • Coverage >90% for component file
  • Event propagation verified for all keyboard events
  • Lifecycle cleanup verified (no leaks)
  • Positioning logic tested for all viewport scenarios
  • bun run test passes without errors
  • Code review approved

Estimated Effort

3-4 hours - Comprehensive test suite with 27+ test cases

Reference Materials

Activity

  1. self-assigned this
    on Oct 5, 2025
  2. added a commit that references this issue on Oct 5, 2025
    14b6ab4
  3. added 4 commits that reference this issue on Feb 4, 2026
    b8cb7cb
    64ac099
    a3e3996
    6cc969e
  4. added 2 commits that reference this issue on Feb 26, 2026
    ca2ebf2
    20a276e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions