MCPcopy Index your code
hub / github.com/TanStack/db / withExpectedRejection

Function withExpectedRejection

packages/db/tests/utils.ts:428–481  ·  view source on GitHub ↗
(
  expectedMessage: string,
  testFn: () => T | Promise<T>,
)

Source from the content-addressed store, hash-verified

426 * ```
427 */
428export function withExpectedRejection<T>(
429 expectedMessage: string,
430 testFn: () => T | Promise<T>,
431): Promise<T> {
432 return new Promise((resolve, reject) => {
433 // Find and temporarily remove the vitest unhandled rejection handler
434 const originalUnhandledRejection = process
435 .listeners(`unhandledRejection`)
436 .find((listener) => listener.name === `vitestUnhandledRejectionHandler`)
437
438 let expectedRejectionCaught = false
439 const handleRejection = (reason: any) => {
440 if (reason?.message === expectedMessage) {
441 expectedRejectionCaught = true
442 return // Don't re-throw, this is expected
443 }
444 // Re-throw other rejections
445 reject(reason)
446 }
447
448 if (originalUnhandledRejection) {
449 process.removeListener(`unhandledRejection`, originalUnhandledRejection)
450 }
451 process.on(`unhandledRejection`, handleRejection)
452
453 // Execute the test function and handle the result
454 Promise.resolve(testFn())
455 .then(async (value) => {
456 // Wait for microtasks and then check if the rejection was caught
457 await flushPromises()
458
459 if (!expectedRejectionCaught) {
460 reject(
461 new Error(
462 `Expected rejection with message "${expectedMessage}" was not caught`,
463 ),
464 )
465 return
466 }
467
468 resolve(value)
469 })
470 .catch((error) => {
471 reject(error)
472 })
473 .finally(() => {
474 // Clean up the error handler
475 process.removeListener(`unhandledRejection`, handleRejection)
476 if (originalUnhandledRejection) {
477 process.addListener(`unhandledRejection`, originalUnhandledRejection)
478 }
479 })
480 })
481}

Callers 1

collection.test.tsFile · 0.90

Calls 3

testFnFunction · 0.85
flushPromisesFunction · 0.70
onMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…