TestUtils.jsm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /*
  5. * This module implements a number of utilities useful for testing.
  6. *
  7. * Additions to this module should be generic and useful to testing multiple
  8. * features. Utilities only useful to a sepcific testing framework should live
  9. * in a module specific to that framework, such as BrowserTestUtils.jsm in the
  10. * case of mochitest-browser-chrome.
  11. */
  12. "use strict";
  13. this.EXPORTED_SYMBOLS = [
  14. "TestUtils",
  15. ];
  16. const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
  17. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  18. Cu.import("resource://gre/modules/Services.jsm");
  19. this.TestUtils = {
  20. executeSoon(callbackFn) {
  21. Services.tm.mainThread.dispatch(callbackFn, Ci.nsIThread.DISPATCH_NORMAL);
  22. },
  23. /**
  24. * Waits for the specified topic to be observed.
  25. *
  26. * @param {string} topic
  27. * The topic to observe.
  28. * @param {function} checkFn [optional]
  29. * Called with (subject, data) as arguments, should return true if the
  30. * notification is the expected one, or false if it should be ignored
  31. * and listening should continue. If not specified, the first
  32. * notification for the specified topic resolves the returned promise.
  33. *
  34. * @note Because this function is intended for testing, any error in checkFn
  35. * will cause the returned promise to be rejected instead of waiting for
  36. * the next notification, since this is probably a bug in the test.
  37. *
  38. * @return {Promise}
  39. * @resolves The array [subject, data] from the observed notification.
  40. */
  41. topicObserved(topic, checkFn) {
  42. return new Promise((resolve, reject) => {
  43. Services.obs.addObserver(function observer(subject, topic, data) {
  44. try {
  45. if (checkFn && !checkFn(subject, data)) {
  46. return;
  47. }
  48. Services.obs.removeObserver(observer, topic);
  49. resolve([subject, data]);
  50. } catch (ex) {
  51. Services.obs.removeObserver(observer, topic);
  52. reject(ex);
  53. }
  54. }, topic, false);
  55. });
  56. },
  57. };