await-running-jobs.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { SimpleGraphQLClient } from '@vendure/testing';
  2. import { GetRunningJobsQuery, GetRunningJobsQueryVariables } from '../graphql/generated-e2e-admin-types';
  3. import { GET_RUNNING_JOBS } 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. GET_RUNNING_JOBS,
  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. }