Utilizziamo i cookie per migliorare la tua esperienza sul sito
CodeWorlds

Testy jednostkowe dla event handlerów

Jak testować kod związany z obsługą wydarzeń.

Testowanie wydarzeń

1// Przykład testów z Jest
2describe('Event Handlers', () => {
3  let mockElement;
4  let eventHandler;
5
6  beforeEach(() => {
7    // Tworzenie mock elementu DOM
8    mockElement = {
9      addEventListener: jest.fn(),
10      removeEventListener: jest.fn(),
11      dispatchEvent: jest.fn()
12    };
13
14    // Mock funkcji globalnych
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    // Symulacja wydarzenia
35    const mockEvent = {
36      target: { dataset: { dinoId: '123' } },
37      preventDefault: jest.fn()
38    };
39
40    // Wywołanie handlera bezpośrednio
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// Test integracyjny z rzeczywistym DOM
72describe('Integration Tests', () => {
73  test('should handle real DOM events', () => {
74    // Tworzenie rzeczywistego elementu
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    // Symulacja kliknięcia
84    button.click();
85
86    expect(clickCount).toBe(1);
87
88    // Cleanup
89    document.body.removeChild(button);
90  });
91});
Vai a CodeWorlds