shared-redux-head.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
  2. /* Any copyright is dedicated to the Public Domain.
  3. * http://creativecommons.org/publicdomain/zero/1.0/ */
  4. "use strict";
  5. /* eslint no-unused-vars: [2, {"vars": "local"}] */
  6. /* import-globals-from ./shared-head.js */
  7. // Currently this file expects "defer" to be imported into scope.
  8. // Common utility functions for working with Redux stores. The file is meant
  9. // to be safe to load in both mochitest and xpcshell environments.
  10. /**
  11. * A logging function that can be used from xpcshell and browser mochitest
  12. * environments.
  13. */
  14. function commonLog(message) {
  15. let log;
  16. if (Services && Services.appinfo && Services.appinfo.name &&
  17. Services.appinfo.name == "Firefox") {
  18. log = info;
  19. } else {
  20. log = do_print;
  21. }
  22. log(message);
  23. }
  24. /**
  25. * Wait until the store has reached a state that matches the predicate.
  26. * @param Store store
  27. * The Redux store being used.
  28. * @param function predicate
  29. * A function that returns true when the store has reached the expected
  30. * state.
  31. * @return Promise
  32. * Resolved once the store reaches the expected state.
  33. */
  34. function waitUntilState(store, predicate) {
  35. let deferred = defer();
  36. let unsubscribe = store.subscribe(check);
  37. commonLog(`Waiting for state predicate "${predicate}"`);
  38. function check() {
  39. if (predicate(store.getState())) {
  40. commonLog(`Found state predicate "${predicate}"`);
  41. unsubscribe();
  42. deferred.resolve();
  43. }
  44. }
  45. // Fire the check immediately in case the action has already occurred
  46. check();
  47. return deferred.promise;
  48. }
  49. /**
  50. * Wait until a particular action has been emitted by the store.
  51. * @param Store store
  52. * The Redux store being used.
  53. * @param string actionType
  54. * The expected action to wait for.
  55. * @return Promise
  56. * Resolved once the expected action is emitted by the store.
  57. */
  58. function waitUntilAction(store, actionType) {
  59. let deferred = defer();
  60. let unsubscribe = store.subscribe(check);
  61. let history = store.history;
  62. let index = history.length;
  63. commonLog(`Waiting for action "${actionType}"`);
  64. function check() {
  65. let action = history[index++];
  66. if (action && action.type === actionType) {
  67. commonLog(`Found action "${actionType}"`);
  68. unsubscribe();
  69. deferred.resolve(store.getState());
  70. }
  71. }
  72. return deferred.promise;
  73. }