async-spec-helpers.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. exports.beforeEach = function (fn) {
  2. global.beforeEach(function () {
  3. const result = fn();
  4. if (result instanceof Promise) {
  5. waitsForPromise(() => result);
  6. }
  7. });
  8. };
  9. exports.afterEach = function (fn) {
  10. global.afterEach(function () {
  11. const result = fn();
  12. if (result instanceof Promise) {
  13. waitsForPromise(() => result);
  14. }
  15. });
  16. };
  17. for (const name of ['it', 'fit', 'ffit', 'fffit']) {
  18. exports[name] = function (description, fn) {
  19. if (fn === undefined) {
  20. global[name](description);
  21. return;
  22. }
  23. global[name](description, function () {
  24. const result = fn();
  25. if (result instanceof Promise) {
  26. waitsForPromise(() => result);
  27. }
  28. });
  29. };
  30. }
  31. exports.conditionPromise = async function (
  32. condition,
  33. description = condition.toString()
  34. ) {
  35. const startTime = Date.now();
  36. while (true) {
  37. await exports.timeoutPromise(100);
  38. if (await condition()) {
  39. return;
  40. }
  41. if (Date.now() - startTime > 120000) {
  42. throw new Error('Timed out waiting on ' + description);
  43. }
  44. }
  45. };
  46. exports.timeoutPromise = function (timeout) {
  47. return new Promise(function (resolve) {
  48. global.setTimeout(resolve, timeout);
  49. });
  50. };
  51. exports.waitsForPromise = function (fn) {
  52. const promise = fn();
  53. global.waitsFor('spec promise to resolve', function (done) {
  54. promise.then(done, function (error) {
  55. jasmine.getEnv().currentSpec.fail(error);
  56. done();
  57. });
  58. });
  59. };