Advanced JavaScript

Master advanced JavaScript concepts including design patterns, performance optimization, and modern development practices.

advanced JavaScript 7 hours

Chapter 14: Testing Advanced JavaScript

Chapter 14 of 15

Chapter 14: Testing Advanced JavaScript

14.1 Unit Testing

Unit tests verify that individual functions and modules work correctly in isolation.

// Using Jest
describe('Math functions', () => {
    test('adds two numbers', () => {
        expect(add(2, 3)).toBe(5);
    });
    
    test('handles negative numbers', () => {
        expect(add(-1, -2)).toBe(-3);
    });
    
    test('throws error for invalid input', () => {
        expect(() => add('a', 2)).toThrow();
    });
});

Testing Async Code:

// Async/await
test('fetches user data', async () => {
    const user = await fetchUser(1);
    expect(user).toHaveProperty('id');
    expect(user.id).toBe(1);
});

// Promises
test('handles promise rejection', () => {
    return expect(fetchUser(999)).rejects.toThrow('User not found');
});

14.2 Integration Testing

// Test multiple components together
describe('User API Integration', () => {
    test('creates and retrieves user', async () => {
        const user = await createUser({ name: 'John' });
        const retrieved = await getUser(user.id);
        expect(retrieved.name).toBe('John');
    });
});

14.3 Mocking and Stubs

// Mock functions
const mockFetch = jest.fn();
mockFetch.mockResolvedValue({ json: () => ({ id: 1 }) });

// Mock modules
jest.mock('./api', () => ({
    fetchUser: jest.fn()
}));

14.4 Test Coverage

// Jest coverage
// Run: jest --coverage
// Measures:
// - Statement coverage
// - Branch coverage
// - Function coverage
// - Line coverage