-
-
Save casey-chow/dd580756adea0d3c9940490803d9c0d0 to your computer and use it in GitHub Desktop.
waitForSubscription helper function for testing graphql subscriptions
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
/** | |
* Waits for a subscription after a trigger function is called. The trigger function is delayed to | |
* properly time the subscription return event. | |
*/ | |
const waitForSubscription = async <TResult = any>( | |
subscription: DocumentNode, | |
trigger: () => Promise<void> | |
): Promise<ExecutionResult<TResult>> => { | |
const iterator = await subscribe<TResult>( | |
schema, | |
subscription, | |
{}, | |
isFunction(options.context) | |
? options.context({} as ExpressContext) | |
: options.context | |
); | |
if (!isAsyncIterable(iterator)) { | |
return iterator; | |
} | |
const [res] = await Promise.all([ | |
(async () => { | |
for await (const next of iterator) { | |
return next; | |
} | |
throw new Error('iterator completed without returning a result'); | |
})(), | |
(async () => { | |
// ensure that trigger occurs after the iterator begins | |
await nextTick(); | |
await trigger(); | |
})(), | |
]); | |
return res; | |
}; |
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
export async function waitForSubscription<TResult, TContext>( | |
subscription: DocumentNode, | |
context: TContext | |
): Promise<ExecutionResult<TResult>> { | |
const iterator = await subscribe<TResult>(schema, subscription, {}, context); | |
if (!isAsyncIterable(iterator)) { | |
return iterator; | |
} | |
for await (const next of iterator) { | |
return next; | |
} | |
throw new Error('iterator completed without returning a result'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I updated this with the following changes from the fork:
ExecutionResult
which has a similar shape toapollo-server-testing
's results, so tests can be a bit more consistent.new Promise
, it's just an async function now.