use-swr-cache.test.tsx


Overview

This file contains comprehensive test suites for verifying the behavior, correctness, and flexibility of the caching mechanism in the useSWR React hook from the SWR library. It specifically focuses on:

The tests leverage React Testing Library and utilities to simulate component rendering, user interactions, and asynchronous state updates.


Detailed Explanation of Test Suites and Key Functions

Imported Utilities and Hooks


Test Suite: useSWR - cache provider

This suite tests behaviors when using custom cache providers (i.e., caches supplied via provider option or SWRConfig).

Key Test Cases

  1. Cache update propagation

    • Verifies that cache updates propagate correctly when switching between keys.

    • Usage: Renders a component that switches between two keys on click; asserts cache contents before and after.

  2. Initial cache reads with subsequent updates

    • Ensures data initially read from cache correctly updates after asynchronous fetches.

  3. Direct mutation of cache data

    • Uses mutate from useSWRConfig to directly change cached data and verifies UI reflects this immediately.

  4. Multi-level cache support

    • Shows nested components can use different cache providers, resulting in different data for the same cache key.

  5. Isolated cache instances

    • Ensures that multiple SWRConfig providers with different caches isolate state correctly.

  6. Provider options respect (initFocus, initReconnect)

    • Tests that lifecycle hooks for focus and reconnect events are called and unsubscribed properly.

  7. Revalidate on focus works

    • Confirms that data is revalidated when window gains focus, considering throttling intervals.

  8. Fallback values with custom provider

    • Verifies fallback cache values are used immediately before fetch completion.

  9. Fallback ignored if cache exists

    • Tests fallback values do not override existing cached data.

  10. Parent cache extension

    • Demonstrates how a custom provider can wrap and extend the parent cache's behavior (e.g., by appending text to cached data).

  11. Cache instance access via useSWRConfig

    • Confirms that the cache instance returned from the hook matches the provided cache.

  12. Cache hierarchy correctness

    • Ensures nested SWRConfig components maintain correct fallback and cache precedence.

  13. Cache provider instance reuse on rerender

    • Validates that the cache provider function is not called multiple times unnecessarily during rerenders.


Test Suite: useSWR - global cache

This suite tests behaviors using the global cache instance that SWR provides by default.

Key Test Cases

  1. Global cache and mutate by default

    • Confirms that useSWRConfig() returns the global cache and mutate function.

  2. Updating the global cache

    • Similar to custom provider tests but with global cache, verifies cache updates on key changes.

  3. Mutate cached value globally

    • Uses mutate from global config to update cache and verifies UI.

  4. Revalidation on focus with global cache

    • Tests revalidate on window focus behavior with the global cache.

  5. Fallback values supported globally

    • Verifies fallback values work as expected with global cache.

  6. Cache instance reuse after unmounting SWRConfig

    • Tests that cache and event listeners persist correctly even when SWRConfig is unmounted and remounted.

  7. Correct cache instance under React Strict Mode

    • Ensures cache works correctly when components are wrapped in React's StrictMode.


Important Implementation Details and Algorithms


Interaction With Other System Parts


Usage Examples

Example 1: Updating cache on interaction

function Page() {
  const [index, setIndex] = useState(0)
  const { data } = useSWR(keys[index], key => 'res:' + key)

  return <div onClick={() => setIndex(1)}>{data}</div>
}

// Renders initially data for keys[0], then updates to keys[1] on click
renderWithConfig(<Page />, { provider: () => new Map() })

Example 2: Using multi-level caches

function Foo() {
  const { data } = useSWR(key, null)
  return <>{data}</>
}

function Page() {
  const { data } = useSWR(key, null)
  return (
    <div>
      {data}:
      <SWRConfig value={{ provider: () => new Map([[key, { data: '2' }]]) }}>
        <Foo />
      </SWRConfig>
    </div>
  )
}

Visual Diagram: Component and Cache Interaction Flow

flowchart TD
    A[Page Component] -->|useSWR(key1)| B[Cache Provider 1]
    A -->|SWRConfig| C[Child Component Foo]
    C -->|useSWR(key1)| D[Cache Provider 2]
    B -->|provides cache data| A
    D -->|provides cache data| C
    E[Global Cache] -->|Default cache| F[useSWRConfig hook]
    style B fill:#f9f,stroke:#333,stroke-width:1px
    style D fill:#bbf,stroke:#333,stroke-width:1px
    style E fill:#afa,stroke:#333,stroke-width:1px

Summary

The use-swr-cache.test.tsx file is a robust test suite validating the caching layer of the SWR React hook. It ensures that:

These tests are vital to maintaining the integrity and flexibility of SWR's caching mechanism in complex React applications.