We use cookies to enhance your experience on the site
CodeWorlds

Unit Tests for Event Handlers

How to test code related to event handling.

Testing Events

1// Example tests with Jest
2describe('Event Handlers', () => {
3  let mockElement;
4  let eventHandler;
5
6  beforeEach(() => {
7    // Creating a mock DOM element
8    mockElement = {
9      addEventListener: jest.fn(),
10      removeEventListener: jest.fn(),
11      dispatchEvent: jest.fn()
12    };
13
14    // Mock global functions
15    global.document = {
16      getElementById: jest.fn(() => mockElement),
17      createElement: jest.fn(() => mockElement)
18    };
19  });
20
21  test('should add event listener on init', () => {
22    const handler = new DinosaurCardHandler(mockElement);
23
24    expect(mockElement.addEventListener).toHaveBeenCalledWith(
25      'click',
26      expect.any(Function)
27    );
28  });
29
30  test('should handle click event correctly', () => {
31    const mockCallback = jest.fn();
32    const handler = new DinosaurCardHandler(mockElement);
33
34    // Event simulation
35    const mockEvent = {
36      target: { dataset: { dinoId: '123' } },
37      preventDefault: jest.fn()
38    };
39
40    // Calling the handler directly
41    handler.handleClick(mockEvent);
42
43    expect(mockEvent.preventDefault).toHaveBeenCalled();
44  });
45
46  test('should remove event listener on destroy', () => {
47    const handler = new DinosaurCardHandler(mockElement);
48    handler.destroy();
49
50    expect(mockElement.removeEventListener).toHaveBeenCalledWith(
51      'click',
52      expect.any(Function)
53    );
54  });
55
56  test('should emit custom event', () => {
57    const handler = new DinosaurCardHandler(mockElement);
58    const customEvent = new CustomEvent('dinosaurSelected');
59
60    handler.emitDinosaurSelected('123');
61
62    expect(mockElement.dispatchEvent).toHaveBeenCalledWith(
63      expect.objectContaining({
64        type: 'dinosaurSelected',
65        detail: { dinosaurId: '123' }
66      })
67    );
68  });
69});
70
71// Integration test with real DOM
72describe('Integration Tests', () => {
73  test('should handle real DOM events', () => {
74    // Creating a real element
75    const button = document.createElement('button');
76    document.body.appendChild(button);
77
78    let clickCount = 0;
79    button.addEventListener('click', () => {
80      clickCount++;
81    });
82
83    // Simulating a click
84    button.click();
85
86    expect(clickCount).toBe(1);
87
88    // Cleanup
89    document.body.removeChild(button);
90  });
91});
Go to CodeWorlds