Skip to content

Clean up the better-auth session store at the end of every test file - #231

Open
Skyfay wants to merge 1 commit into
devfrom
Skyfay/auth-test-flake
Open

Skyfay wants to merge 1 commit into
devfrom
Skyfay/auth-test-flake

Conversation

@Skyfay

@Skyfay Skyfay commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Problem

Some components read the session through better-auth, which keeps a listener on window. The library removes that listener one second after the last component lets go of it. If a test file ends sooner, the timer is still pending. When the process lives on for that second, as it does while CI writes coverage, the timer fires after Vitest has already removed jsdom. window.removeEventListener no longer exists, and Vitest fails the whole run with an unhandled error even though every test passed.

Fix

The test setup now runs the library's own cleanup for the session stores in an afterAll hook. It runs while window still exists, so the late timer has nothing left to do.

Changes

  • Add src/lib/testing/auth-stores.ts with settleAuthStores(). It finds the mounted session stores of the real auth client and runs their nanostores cleanup right away. It does nothing when a file never loaded the client or replaced it with a mock.
  • Call settleAuthStores() from a new afterAll hook in src/lib/testing/setup.ts.
  • Add tests/unit/lib/auth-stores.test.tsx. It checks two things: the storage listener is removed from window at once after unmount, and nothing happens when no store is mounted.
  • Add the changelog fragment changelog/unreleased/Skyfay-auth-test-flake.md.

A component that reads the session mounts the store of the client, which takes its storage listener off window one second after it was let go. A file that ended sooner left that timer behind, and when its process lived on, as while CI writes the coverage, it fired after jsdom was gone and failed the run on an unhandled error. The test setup now runs that cleanup at the end of each file.
@codecov

codecov Bot commented Nov 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

This branch was successfully deployed

1 active deployment
e2e — cfe5c62c Deployed Nov 28, 2026 by Skyfay via Approve #171
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant