-
Notifications
You must be signed in to change notification settings - Fork 2
fix: catch AbortErrors in storybook tests and patch @reatom/core #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Guria
wants to merge
6
commits into
main
Choose a base branch
from
fix/abort-error-guard-and-reatom-patch
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0e3494b
feat: enable connectLogger in development mode for improved logging
Guria 0fe8f23
feat: implement abort error handling with clear and drain functions
Guria bbf9994
feat: add VITE_CONNECT_LOGGER configuration and improve logger initia…
Guria 878a1f4
fix: catch AbortErrors in storybook tests and patch @reatom/core
Guria fac6e93
test: tighten abort guard and add route loader contract checks
Guria 2170bb9
test: isolate route-mode stories and tighten abort-error assertions
Guria File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import { addGlobalExtension, isAbort, isAction, withCallHook } from '@reatom/core' | ||
|
|
||
| interface CollectedAbortError { | ||
| actionName: string | ||
| message: string | ||
| } | ||
|
|
||
| export interface DrainAbortError extends CollectedAbortError { | ||
| count: number | ||
| } | ||
|
|
||
| interface ExpectedAbortError { | ||
| actionName?: RegExp | string | ||
| message?: RegExp | string | ||
| } | ||
|
|
||
| const collected: CollectedAbortError[] = [] | ||
|
|
||
| export function clearAbortErrors() { | ||
| collected.length = 0 | ||
| } | ||
|
|
||
| export function drainAbortErrors(): DrainAbortError[] { | ||
| const grouped = new Map<string, DrainAbortError>() | ||
|
|
||
| for (const error of collected) { | ||
| const key = `${error.actionName}\u0000${error.message}` | ||
| const existing = grouped.get(key) | ||
| if (existing) existing.count += 1 | ||
| else grouped.set(key, { ...error, count: 1 }) | ||
| } | ||
|
|
||
| collected.length = 0 | ||
| return [...grouped.values()] | ||
| } | ||
|
|
||
| const isMatch = (actual: string, expected: RegExp | string | undefined) => { | ||
| if (!expected) return true | ||
| return typeof expected === 'string' ? actual === expected : expected.test(actual) | ||
| } | ||
|
|
||
| const escapeRegExp = (value: string) => value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&') | ||
|
|
||
| export const formatAbortErrors = (errors: DrainAbortError[]) => | ||
| errors.map((e) => ` - ${e.actionName}: ${e.message} ×${e.count}`).join('\n') | ||
|
|
||
| export function assertOnlyExpectedAbortErrors( | ||
| expected: ExpectedAbortError, | ||
| reason = 'Expected Reatom AbortErrors', | ||
| ) { | ||
| const errors = drainAbortErrors() | ||
| const unexpected = errors.filter( | ||
| (error) => | ||
| !isMatch(error.actionName, expected.actionName) || !isMatch(error.message, expected.message), | ||
| ) | ||
| if (unexpected.length > 0) { | ||
| throw new Error(`${reason} included unexpected AbortErrors:\n${formatAbortErrors(unexpected)}`) | ||
| } | ||
| } | ||
|
|
||
| export async function assertExpectedRouteLoaderTeardownAbort(routeName: string) { | ||
| await Promise.resolve() | ||
| await new Promise<void>((resolve) => queueMicrotask(resolve)) | ||
| assertOnlyExpectedAbortErrors( | ||
| { | ||
| actionName: new RegExp(`${escapeRegExp(routeName)}.*\\.loader\\.onReject$`), | ||
| message: /unmatch/, | ||
| }, | ||
| `Expected ${routeName} matched-route teardown AbortErrors`, | ||
| ) | ||
| } | ||
|
|
||
| addGlobalExtension((target) => { | ||
| if (isAction(target) && target.name.endsWith('.onReject')) { | ||
| target.extend( | ||
| withCallHook((payload) => { | ||
|
Check warning on line 76 in .storybook/abortErrorGuard.ts
|
||
| const error = (payload as { error?: unknown })?.error | ||
| if (error && isAbort(error)) { | ||
| collected.push({ | ||
| actionName: target.name, | ||
| message: String((error as Error).message ?? error), | ||
| }) | ||
| } | ||
| }), | ||
| ) | ||
| } | ||
| return target | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| diff --git a/dist/index.js b/dist/index.js | ||
| index b3110cb9bbe3b771c3b3fa5e9afbd8fd95d4d04b..485372c98b801fd07a9ddfe43d45d7c560dc36fb 100644 | ||
| --- a/dist/index.js | ||
| +++ b/dist/index.js | ||
| @@ -7126,14 +7126,14 @@ const onEvent = (target, type, cb, options) => { | ||
| //#region src/web/url.ts | ||
| /** Create the URL atom with the new Reatom API. */ | ||
| let urlAtom = atom(null, "urlAtom").extend(withMiddleware(() => (next, ...params) => next(...params) ?? urlAtom.init()), withInitHook(() => { | ||
| - for (const [, routeAtom] of Object.entries(urlAtom.routes)) routeAtom.loader(); | ||
| + for (const [, routeAtom] of Object.entries(urlAtom.routes)) if (routeAtom()) routeAtom.loader(); | ||
| }, "effect"), withParams((update, replace = false) => { | ||
| let url = top().state; | ||
| let newUrl = typeof update === "function" ? update(url ?? urlAtom.init()) : update; | ||
| if (newUrl.href === url?.href) return url; | ||
| if (url !== newUrl) { | ||
| _enqueue(() => { | ||
| - for (const [, routeAtom] of Object.entries(urlAtom.routes)) routeAtom.loader(); | ||
| + for (const [, routeAtom] of Object.entries(urlAtom.routes)) if (routeAtom()) routeAtom.loader(); | ||
| }, "compute"); | ||
| if (STACK[STACK.length - 2]?.atom !== urlAtom.syncFromSource) urlAtom.sync()(newUrl, replace); | ||
| } | ||
| @@ -7572,7 +7572,7 @@ let reatomRoute = createRouteFactory(urlAtom); | ||
| * route | ||
| */ | ||
| const is404 = computed(() => Object.values(urlAtom.routes).every((route) => !route()), "is404"); | ||
| -const isSomeLoaderPending = computed(() => Object.values(urlAtom.routes).some((route) => route.loader.pending() > 0), "isSomeLoaderPending"); | ||
| +const isSomeLoaderPending = computed(() => Object.values(urlAtom.routes).some((route) => route.match() && route.loader.pending() > 0), "isSomeLoaderPending"); | ||
| //#endregion | ||
| //#region src/routing/searchParams.ts | ||
| const isSubpath = (currentPath, targetPath) => !targetPath || targetPath[targetPath.length - 1] === "*" ? `${currentPath}/`.startsWith(targetPath.slice(0, -1)) : `${currentPath}/` === targetPath; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| import preview from '#.storybook/preview' | ||
| import { App } from '#app/App' | ||
| import { articleDetail } from '#entities/article/mocks/handlers' | ||
| import { articlesActor as I } from '#pages/articles/testing' | ||
| import { heading, role } from '#shared/test' | ||
|
|
||
| const meta = preview.meta({ | ||
| title: 'Integration/Articles/Detail', | ||
| component: App, | ||
| parameters: { | ||
| layout: 'fullscreen', | ||
| initialPath: 'articles/1', | ||
| }, | ||
| loaders: [(ctx) => I.init(ctx)], | ||
| }) | ||
|
|
||
| export default meta | ||
|
|
||
| export const HandlesArticleDetailServerError = meta.story({ | ||
| name: 'Article Detail Server Error', | ||
| play: () => I.waitExit(role('status')), | ||
| parameters: { | ||
| msw: { | ||
| handlers: { articleDetail: articleDetail.error }, | ||
| }, | ||
| }, | ||
| }) | ||
|
|
||
| HandlesArticleDetailServerError.test( | ||
| 'shows error state when article detail request fails', | ||
| async () => { | ||
| await I.scope(role('main'), async () => { | ||
| await I.seeDetailError() | ||
| }) | ||
| }, | ||
| ) | ||
|
|
||
| HandlesArticleDetailServerError.test('keeps detail error state when retry also fails', async () => { | ||
| await I.scope(role('main'), async () => { | ||
| await I.seeDetailError() | ||
| await I.retry() | ||
| await I.waitExit(role('status')) | ||
| await I.seeDetailError() | ||
| }) | ||
| }) | ||
|
|
||
| export const RecoversAfterArticleDetailRetry = meta.story({ | ||
| name: 'Article Detail Retry Success', | ||
| play: () => I.waitExit(role('status')), | ||
| parameters: { | ||
| msw: { | ||
| handlers: { articleDetail: articleDetail.retrySucceeds() }, | ||
| }, | ||
| }, | ||
| }) | ||
|
|
||
| RecoversAfterArticleDetailRetry.test('loads article detail after retry succeeds', async () => { | ||
| await I.scope(role('main'), async () => { | ||
| await I.seeDetailError() | ||
| await I.retry() | ||
| await I.waitExit(role('status')) | ||
| await I.see(heading('Quarterly report').wait()) | ||
| await I.seeArticleDetail('Quarterly report') | ||
| }) | ||
| }) | ||
|
|
||
| export const HandlesArticleDetailServerErrorMobile = meta.story({ | ||
| name: 'Article Detail Server Error (Mobile)', | ||
| globals: { viewport: { value: 'sm', isRotated: false } }, | ||
| parameters: HandlesArticleDetailServerError.input.parameters, | ||
| play: () => I.waitExit(role('status')), | ||
| }) | ||
|
|
||
| HandlesArticleDetailServerErrorMobile.test( | ||
| '[mobile] shows error state when article detail request fails', | ||
| async () => { | ||
| await I.scope(role('main'), async () => { | ||
| await I.seeDetailError() | ||
| }) | ||
| }, | ||
| ) | ||
|
|
||
| export const KeepsLoadingWhenArticleDetailNeverResolves = meta.story({ | ||
| name: 'Article Detail Loading State', | ||
| parameters: { | ||
| msw: { | ||
| handlers: { articleDetail: articleDetail.loading }, | ||
| }, | ||
| }, | ||
| }) | ||
|
|
||
| KeepsLoadingWhenArticleDetailNeverResolves.test( | ||
| 'shows detail loading state while article detail is pending', | ||
| async () => { | ||
| const detail = await I.see(role('main')) | ||
| await I.seeDetailLoading(detail) | ||
| }, | ||
| ) | ||
|
|
||
| export const KeepsLoadingWhenArticleDetailNeverResolvesMobile = meta.story({ | ||
| name: 'Article Detail Loading State (Mobile)', | ||
| globals: { viewport: { value: 'sm', isRotated: false } }, | ||
| parameters: KeepsLoadingWhenArticleDetailNeverResolves.input.parameters, | ||
| }) | ||
|
|
||
| KeepsLoadingWhenArticleDetailNeverResolvesMobile.test( | ||
| '[mobile] shows detail loading state while article detail is pending', | ||
| async () => { | ||
| const detail = await I.see(role('main')) | ||
| await I.seeDetailLoading(detail) | ||
| }, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import preview from '#.storybook/preview' | ||
| import { App } from '#app/App' | ||
| import { articlesActor as I } from '#pages/articles/testing' | ||
| import { role } from '#shared/test' | ||
|
|
||
| const meta = preview.meta({ | ||
| title: 'Integration/Articles/Direct URL', | ||
| component: App, | ||
| parameters: { | ||
| layout: 'fullscreen', | ||
| initialPath: 'articles/1', | ||
| }, | ||
| loaders: [(ctx) => I.init(ctx)], | ||
| }) | ||
|
|
||
| export default meta | ||
|
|
||
| export const DirectUrlNavigation = meta.story({ | ||
| name: 'Direct URL to Article', | ||
| play: () => I.waitExit(role('status')), | ||
| }) | ||
|
|
||
| DirectUrlNavigation.test('loads article detail directly from URL', async () => { | ||
| await I.seeArticleDetail('Quarterly report') | ||
| await I.seeArticleDetailContent() | ||
| }) | ||
|
|
||
| export const DirectUrlNotFound = meta.story({ | ||
| name: 'Direct URL to Missing Article', | ||
| parameters: { initialPath: 'articles/missing-42' }, | ||
| play: () => I.waitExit(role('status')), | ||
| }) | ||
|
|
||
| DirectUrlNotFound.test('shows not-found state for missing article URL', async () => { | ||
| await I.scope(role('main'), async () => { | ||
| await I.seeArticleNotFound('missing-42') | ||
| }) | ||
| }) | ||
|
|
||
| export const DirectUrlNavigationMobile = meta.story({ | ||
| name: 'Direct URL to Article (Mobile)', | ||
| globals: { viewport: { value: 'sm', isRotated: false } }, | ||
| parameters: { initialPath: 'articles/1' }, | ||
| play: () => I.waitExit(role('status')), | ||
| }) | ||
|
|
||
| DirectUrlNavigationMobile.test('[mobile] loads article detail directly from URL', async () => { | ||
| await I.seeArticleDetail('Quarterly report') | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When navigating away from a route with an in-flight loader, this guard skips calling that route's loader after
routeAtom()becomes null. That removes the proactive recomputation that used to enter the loader, see the unmatch state, and trigger thewithAbort/reject path; with the newisSomeLoaderPendingshort-circuit, unmatched loaders are also no longer kept subscribed viapending(). As a result, slow requests for the previous route can continue and fulfill intoroute.loader.data()after the route is no longer active instead of being aborted on navigation.Useful? React with 👍 / 👎.