queueRunner.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = queueRunner;
  6. var _PCancelable = _interopRequireDefault(require('./PCancelable'));
  7. var _pTimeout = _interopRequireDefault(require('./pTimeout'));
  8. function _interopRequireDefault(obj) {
  9. return obj && obj.__esModule ? obj : {default: obj};
  10. }
  11. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  12. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  13. var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
  14. function queueRunner(options) {
  15. const token = new _PCancelable.default((onCancel, resolve) => {
  16. onCancel(resolve);
  17. });
  18. const mapper = ({fn, timeout, initError = new Error()}) => {
  19. let promise = new Promise(resolve => {
  20. const next = function next(...args) {
  21. const err = args[0];
  22. if (err) {
  23. options.fail.apply(null, args);
  24. }
  25. resolve();
  26. };
  27. next.fail = function(...args) {
  28. options.fail.apply(null, args);
  29. resolve();
  30. };
  31. try {
  32. fn.call(options.userContext, next);
  33. } catch (e) {
  34. options.onException(e);
  35. resolve();
  36. }
  37. });
  38. promise = Promise.race([promise, token]);
  39. if (!timeout) {
  40. return promise;
  41. }
  42. const timeoutMs = timeout();
  43. return (0, _pTimeout.default)(
  44. promise,
  45. timeoutMs,
  46. options.clearTimeout,
  47. options.setTimeout,
  48. () => {
  49. initError.message =
  50. 'Timeout - Async callback was not invoked within the ' +
  51. timeoutMs +
  52. 'ms timeout specified by jest.setTimeout.';
  53. initError.stack = initError.message + initError.stack;
  54. options.onException(initError);
  55. }
  56. );
  57. };
  58. const result = options.queueableFns.reduce(
  59. (promise, fn) => promise.then(() => mapper(fn)),
  60. Promise.resolve()
  61. );
  62. return {
  63. cancel: token.cancel.bind(token),
  64. catch: result.catch.bind(result),
  65. then: result.then.bind(result)
  66. };
  67. }