Skip to content

Commit dfaa8a6

Browse files
authored
fix: ignore "Route is already handled" errors (#40)
1 parent 35295f9 commit dfaa8a6

1 file changed

Lines changed: 35 additions & 9 deletions

File tree

src/fixture.ts

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ class SetupPlaywrightApi extends SetupApi<LifeCycleEventsMap> {
9999
this.options.skipAssetRequests &&
100100
isCommonAssetRequest(fetchRequest)
101101
) {
102-
return route.fallback()
102+
return this.safelyHandleRoute(() => route.fallback())
103103
}
104104

105105
const handlers = this.handlersController
@@ -134,19 +134,21 @@ class SetupPlaywrightApi extends SetupApi<LifeCycleEventsMap> {
134134

135135
if (response) {
136136
if (response.status === 0) {
137-
return route.abort()
137+
return this.safelyHandleRoute(() => route.abort())
138138
}
139139

140-
return route.fulfill({
141-
status: response.status,
142-
headers: Object.fromEntries(response.headers),
143-
body: response.body
144-
? Buffer.from(await response.arrayBuffer())
145-
: undefined,
140+
return this.safelyHandleRoute(async () => {
141+
return route.fulfill({
142+
status: response.status,
143+
headers: Object.fromEntries(response.headers),
144+
body: response.body
145+
? Buffer.from(await response.arrayBuffer())
146+
: undefined,
147+
})
146148
})
147149
}
148150

149-
return route.fallback()
151+
return this.safelyHandleRoute(() => route.fallback())
150152
},
151153
)
152154

@@ -201,6 +203,30 @@ class SetupPlaywrightApi extends SetupApi<LifeCycleEventsMap> {
201203
// Encode/decode to preserve escape characters.
202204
return decodeURI(new URL(encodeURI(url)).origin)
203205
}
206+
207+
private async safelyHandleRoute(
208+
callback: () => Promise<void>,
209+
): Promise<void> {
210+
try {
211+
await callback()
212+
} catch (error) {
213+
/**
214+
* @note Ignore "Route is already handled!" errors.
215+
* Playwright has a bug where requests terminated due to navigation
216+
* cause your in-flight route handlers to throw. There's no means to
217+
* detect that scenario as both "route.handled" and "route._handlingPromise" are internal.
218+
* @see https://github.com/mswjs/playwright/issues/35
219+
*/
220+
if (
221+
error instanceof Error &&
222+
/route is already handled/i.test(error.message)
223+
) {
224+
return
225+
}
226+
227+
throw error
228+
}
229+
}
204230
}
205231

206232
class PlaywrightWebSocketClientConnection implements WebSocketClientConnectionProtocol {

0 commit comments

Comments
 (0)