5.6 Testing JavaScript

We write unit tests for complex JavaScript functionality using Jest or similar testing frameworks. Tests should cover both happy path scenarios and error conditions to ensure robust functionality.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Example test for gallery component
describe('ImageGallery', () => {
    let gallery;
    let mockElement;

    beforeEach(() => {
        mockElement = document.createElement('div');
        mockElement.innerHTML = `
            <img class="gallery-image" src="image1.jpg">
            <img class="gallery-image" src="image2.jpg">
            <button class="gallery-next">Next</button>
            <button class="gallery-prev">Previous</button>
        `;

        gallery = new ImageGallery(mockElement);
    });

    test('initializes with first image active', () => {
        expect(gallery.currentIndex).toBe(0);
        expect(mockElement.querySelector('.gallery-image').classList.contains('active')).toBe(true);
    });

    test('advances to next image when next() called', () => {
        gallery.next();
        expect(gallery.currentIndex).toBe(1);
    });
    test('wraps to first image after last image', () => {
        gallery.currentIndex = 1;
        gallery.next();
        expect(gallery.currentIndex).toBe(0);
    });
});

Copyright © 2025 Crowd Favorite. All rights reserved.

This site uses Just the Docs, a documentation theme for Jekyll.