Skip to content

Instantly share code, notes, and snippets.

@casey-chow
Forked from blocka/wait-for-subscription.ts
Last active November 24, 2020 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save casey-chow/dd580756adea0d3c9940490803d9c0d0 to your computer and use it in GitHub Desktop.
Save casey-chow/dd580756adea0d3c9940490803d9c0d0 to your computer and use it in GitHub Desktop.
waitForSubscription helper function for testing graphql subscriptions
/**
* 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;
};
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');
}
@casey-chow
Copy link
Author

I updated this with the following changes from the fork:

  1. It returns an ExecutionResult which has a similar shape to apollo-server-testing's results, so tests can be a bit more consistent.
  2. Rearranged it so there's no need for new Promise, it's just an async function now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment