await-running-jobs.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { SimpleGraphQLClient } from '@vendure/testing';
  2. import { GetRunningJobsQuery, GetRunningJobsQueryVariables } from '../graphql/generated-e2e-admin-types';
  3. import { getRunningJobsDocument } from '../graphql/shared-definitions';
  4. /**
  5. * For mutation which trigger background jobs, this can be used to "pause" the execution of
  6. * the test until those jobs have completed;
  7. */
  8. export async function awaitRunningJobs(
  9. adminClient: SimpleGraphQLClient,
  10. timeout: number = 5000,
  11. delay = 100,
  12. ) {
  13. let runningJobs = 0;
  14. const startTime = +new Date();
  15. let timedOut = false;
  16. // Allow a brief period for the jobs to start in the case that
  17. // e.g. event debouncing is used before triggering the job.
  18. await new Promise(resolve => setTimeout(resolve, delay));
  19. do {
  20. const { jobs } = await adminClient.query<GetRunningJobsQuery, GetRunningJobsQueryVariables>(
  21. getRunningJobsDocument,
  22. {
  23. options: {
  24. filter: {
  25. isSettled: {
  26. eq: false,
  27. },
  28. },
  29. },
  30. },
  31. );
  32. runningJobs = jobs.totalItems;
  33. timedOut = timeout < +new Date() - startTime;
  34. } while (runningJobs > 0 && !timedOut);
  35. if (runningJobs > 0) {
  36. /* eslint-disable no-console */
  37. console.log(`awaitRunningJobs time out with ${runningJobs} jobs still running`);
  38. }
  39. }