web-preset.test.ts


Overview

The web-preset.test.ts file is a Jest test suite designed to verify the behavior of the web preset focus event initialization logic within the SWR library's internal configuration. It tests how the initFocus function reacts to browser environment events on the global window and document objects, specifically focusing on event listeners for focus and visibilitychange events.

The tests ensure that:

This file simulates browser event targets using a custom helper function and mocks global objects to create isolated test environments.


Detailed Explanation

Constants

Function: createEventTarget()

Creates a mock event target object that mimics browser event targets by extending Node.js's EventEmitter with DOM-like addEventListener and removeEventListener methods.

Implementation Details

Return Value

Usage Example

const target = createEventTarget();
target.addEventListener('focus', () => console.log('Focused'));
target.emit('focus'); // Logs "Focused"

Function: runTests(propertyName: string)

Sets up and runs a Jest test suite for either the window or document global object, testing the behavior of initFocus in different environments.

Parameters

Behavior

Usage Example

runTests('window');   // Runs tests on the window object behavior
runTests('document'); // Runs tests on the document object behavior

Important Implementation Details


Interaction with Other Parts of the System


Mermaid Diagram

flowchart TD
    A[runTests(propertyName)] -->|calls| B[createEventTarget()]
    A --> C[Mocks global[propertyName]]
    A --> D[Imports initFocus from swr/_internal]
    A --> E[Sets up Jest test suite]
    E --> F[Test: triggers listener if browser API exists]
    E --> G[Test: does not trigger listener if falsy API]
    B --> H[Extended EventEmitter]
    H --> I[addEventListener = on]
    H --> J[removeEventListener = off]
    F --> K[emit event triggers callback]
    G --> L[emit event does not trigger callback]

Summary

The web-preset.test.ts file is a focused test suite validating that SWR's initFocus correctly attaches and detaches event listeners to browser global objects (window and document). It ensures that focus and visibility change events trigger configured callbacks only when appropriate browser APIs are present. The approach uses Jest for mocking and Node.js's EventEmitter to simulate browser event targets in a controlled testing environment. This file is an essential part of the SWR library's testing strategy to maintain reliable focus event handling across different web contexts.