Skip to content

Latest commit

 

History

History
51 lines (43 loc) · 1.54 KB

testing-javascript.md

File metadata and controls

51 lines (43 loc) · 1.54 KB
layout default
title Testing JavaScript
description We write unit tests for complex JavaScript functionality using Jest or similar testing frameworks...
section JavaScript
section_slug javascript
parent JavaScript
nav_order 6
permalink /javascript/testing-javascript/

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.

// 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);
    });
});