Skip to content

chore: Wrap async state updates in act() for useShareTarget tests #102

@kevalyq

Description

@kevalyq

Context

During the PWA Phase 3 implementation (PR #100), React Testing Library warnings appeared in test output:

stderr | src/hooks/useShareTarget.test.ts > useShareTarget > should clear shared data
Warning: An update to TestComponent inside a test was not wrapped in act(...)

stderr | src/hooks/useShareTarget.test.ts > useShareTarget > should handle multiple share events
Warning: An update to TestComponent inside a test was not wrapped in act(...)

These warnings indicate that asynchronous state updates in tests are not properly wrapped in React's act() utility. While the tests currently pass (131/131 ✅), these warnings should be addressed to:

  • Ensure robust test reliability
  • Prevent potential false positives/negatives in the future
  • Follow React Testing Library best practices

Affected Tests

File: src/hooks/useShareTarget.test.ts

  • Test: "should clear shared data"
  • Test: "should handle multiple share events"

Both tests trigger state updates that React Testing Library detects as unwrapped.

Recommended Solution

Wrap async state updates in act() from @testing-library/react:

import { renderHook, act } from "@testing-library/react";

it("should clear shared data", async () => {
  const { result } = renderHook(() => useShareTarget());
  
  // Wrap state updates in act()
  await act(async () => {
    result.current.clearSharedData();
  });
  
  expect(result.current.sharedData).toBeNull();
});

Alternatively, use waitFor() if updates are truly asynchronous:

import { renderHook, waitFor } from "@testing-library/react";

it("should handle multiple share events", async () => {
  const { result } = renderHook(() => useShareTarget());
  
  await waitFor(() => {
    expect(result.current.sharedData).toBeDefined();
  });
});

Tasks

  • Review src/hooks/useShareTarget.test.ts for unwrapped state updates
  • Identify all locations where result.current methods cause state changes
  • Wrap state-changing calls in act() or waitFor()
  • Verify all tests still pass (should remain 11/11 for this file)
  • Run full test suite to ensure no regressions
  • Update test documentation if patterns change

References

Priority

Low - Tests are functional and passing. This is a code quality improvement to prevent potential future issues and eliminate noise in test output.

Labels

chore, tests, tech-debt

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    ✅ Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions