helpers.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Navigation helper for the test iframe. Queues navigation actions and
  2. // callbacks, then executes them serially with respect to async. This is to
  3. // avoid deep nesting of callbacks in tests.
  4. //
  5. // If a `then`able object is returned from a callback, then the navigation will
  6. // resume only after the promise has been resolved.
  7. //
  8. // After last successful navigation, asyncTest is automatically resumed.
  9. //
  10. // Usage:
  11. //
  12. // navigate(this.frame)
  13. // .pjax(pjaxOptions, function(frame){ ... }
  14. // .back(-1, function(frame){ ... }
  15. //
  16. function navigate(frame) {
  17. var queue = []
  18. var api = {}
  19. api.pjax = function(options, callback) {
  20. queue.push([options, callback])
  21. return api
  22. }
  23. api.back = api.pjax
  24. var workOff = function() {
  25. var item = queue.shift()
  26. if (!item) {
  27. start()
  28. return
  29. }
  30. var target = item[0], callback = item[1]
  31. frame.$(frame.document).one("pjax:end", function() {
  32. var promise = callback && callback(frame)
  33. if (promise && typeof promise.then == "function") promise.then(workOff)
  34. else setTimeout(workOff, 0)
  35. })
  36. if (typeof target == "number") {
  37. frame.history.go(target)
  38. } else {
  39. frame.$.pjax(target)
  40. }
  41. }
  42. setTimeout(workOff, 0)
  43. return api
  44. }
  45. // A poor man's Promise implementation. Only resolvable promises with no
  46. // reject/catch support.
  47. function PoorMansPromise(setup) {
  48. var result, callback, i = 0, callbacks = []
  49. setup(function(_result) {
  50. result = _result
  51. while (callback = callbacks[i++]) callback(result)
  52. })
  53. this.then = function(done) {
  54. if (i == 0) callbacks.push(done)
  55. else setTimeout(function(){ done(result) }, 0)
  56. return this
  57. }
  58. }