flakyIt.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Adapted from https://github.com/bluzi/jest-retries/blob/01a9713a7379edcfd2d1bccec7c0fbc66d4602da/src/retry.js
  2. // We explicitly reference the jest typings since the jest.d.ts file shipped
  3. // with jest 26 masks the @types/jest typings
  4. /// <reference types="jest" />
  5. import { sleep } from './common';
  6. /**
  7. * Run a test function.
  8. *
  9. * @param fn The function of the test
  10. */
  11. async function runTest(fn: any): Promise<void> {
  12. return new Promise((resolve, reject) => {
  13. const result = fn((err: Error) => (err ? reject(err) : resolve()));
  14. if (result && result.then) {
  15. result.catch(reject).then(resolve);
  16. } else {
  17. resolve();
  18. }
  19. });
  20. }
  21. /**
  22. * Run a flaky test with retries.
  23. *
  24. * @param name The name of the test
  25. * @param fn The function of the test
  26. * @param retries The number of retries
  27. * @param wait The time to wait in milliseconds between retries
  28. */
  29. /* eslint-disable jest/no-export */
  30. export function flakyIt(name: string, fn: any, retries = 3, wait = 1000): void {
  31. test(name, async () => {
  32. let latestError;
  33. for (let tries = 0; tries < retries; tries++) {
  34. try {
  35. await runTest(fn);
  36. return;
  37. } catch (error) {
  38. latestError = error;
  39. await sleep(wait);
  40. }
  41. }
  42. throw latestError;
  43. });
  44. }
  45. /* eslint-enable jest/no-export */
  46. flakyIt.only = it.only;
  47. flakyIt.skip = it.skip;
  48. flakyIt.todo = it.todo;