Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Mocking Browser APIs

1. Introduction

Mocking Browser APIs is an essential technique in testing and debugging web applications. It allows developers to simulate the behavior of browser APIs to ensure that code interacts correctly without needing to rely on actual browser functionality.

2. Key Concepts

What is Mocking?

Mocking involves creating a simulated version of an API or object, allowing you to control its behavior and test how your code interacts with it.

Why Mock Browser APIs?

  • To isolate components for testing.
  • To avoid side effects in tests.
  • To speed up test execution.

3. Mocking Techniques

Using Jest for Mocking

Jest is a popular testing framework that provides built-in mocking capabilities. You can easily mock browser APIs using Jest's jest.fn() or jest.mock().


import { fetchData } from './api';

jest.mock('./api');

test('fetches successfully data from an API', async () => {
    const data = { id: 1, title: 'Mocked Title' };
    fetchData.mockResolvedValue(data);
    
    const result = await fetchData();
    expect(result).toEqual(data);
});
                

Mocking Built-In Browser APIs

For example, to mock localStorage:


describe('localStorage mock', () => {
    let setItemMock;

    beforeEach(() => {
        setItemMock = jest.spyOn(Storage.prototype, 'setItem');
    });

    afterEach(() => {
        setItemMock.mockRestore();
    });

    test('should call localStorage.setItem', () => {
        localStorage.setItem('key', 'value');
        expect(setItemMock).toHaveBeenCalledWith('key', 'value');
    });
});
                

4. Best Practices

  • Always clean up mocks after tests to avoid side effects.
  • Use TypeScript definitions for better type safety when mocking.
  • Keep your mocks as close to the actual implementation as possible.

5. FAQ

What is the difference between mocking and stubbing?

Mocking is a more advanced form of testing that verifies interactions, while stubbing is simply replacing a function with a predetermined response.

Can I mock third-party libraries?

Yes, you can mock third-party libraries in your tests to control their behavior and ensure your code handles their responses correctly.

How do I test asynchronous code with mocks?

Use async/await in combination with mocked functions to handle promises and async operations in your tests.