utils.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import {IntlProvider, intlShape} from "react-intl";
  2. import {mount, shallow} from "enzyme";
  3. import React from "react";
  4. const messages = require("data/locales.json")["en-US"]; // eslint-disable-line import/no-commonjs
  5. const intlProvider = new IntlProvider({locale: "en-US", messages});
  6. const {intl} = intlProvider.getChildContext();
  7. /**
  8. * GlobalOverrider - Utility that allows you to override properties on the global object.
  9. * See unit-entry.js for example usage.
  10. */
  11. export class GlobalOverrider {
  12. constructor() {
  13. this.originalGlobals = new Map();
  14. this.sandbox = sinon.createSandbox();
  15. }
  16. /**
  17. * _override - Internal method to override properties on the global object.
  18. * The first time a given key is overridden, we cache the original
  19. * value in this.originalGlobals so that later it can be restored.
  20. *
  21. * @param {string} key The identifier of the property
  22. * @param {any} value The value to which the property should be reassigned
  23. */
  24. _override(key, value) {
  25. if (!this.originalGlobals.has(key)) {
  26. this.originalGlobals.set(key, global[key]);
  27. }
  28. global[key] = value;
  29. }
  30. /**
  31. * set - Override a given property, or all properties on an object
  32. *
  33. * @param {string|object} key If a string, the identifier of the property
  34. * If an object, a number of properties and values to which they should be reassigned.
  35. * @param {any} value The value to which the property should be reassigned
  36. * @return {type} description
  37. */
  38. set(key, value) {
  39. if (!value && typeof key === "object") {
  40. const overrides = key;
  41. Object.keys(overrides).forEach(k => this._override(k, overrides[k]));
  42. } else {
  43. this._override(key, value);
  44. }
  45. return value;
  46. }
  47. /**
  48. * reset - Reset the global sandbox, so all state on spies, stubs etc. is cleared.
  49. * You probably want to call this after each test.
  50. */
  51. reset() {
  52. this.sandbox.reset();
  53. }
  54. /**
  55. * restore - Restore the global sandbox and reset all overriden properties to
  56. * their original values. You should call this after all tests have completed.
  57. */
  58. restore() {
  59. this.sandbox.restore();
  60. this.originalGlobals.forEach((value, key) => {
  61. global[key] = value;
  62. });
  63. }
  64. }
  65. /**
  66. * Very simple fake for the most basic semantics of nsIPrefBranch. Lots of
  67. * things aren't yet supported. Feel free to add them in.
  68. *
  69. * @param {Object} args - optional arguments
  70. * @param {Function} args.initHook - if present, will be called back
  71. * inside the constructor. Typically used from tests
  72. * to save off a pointer to the created instance so that
  73. * stubs and spies can be inspected by the test code.
  74. */
  75. export class FakensIPrefBranch {
  76. constructor(args) {
  77. if (args) {
  78. if ("initHook" in args) {
  79. args.initHook.call(this);
  80. }
  81. }
  82. this._prefBranch = {};
  83. this.observers = {};
  84. }
  85. addObserver(prefName, callback) {
  86. this.observers[prefName] = callback;
  87. }
  88. removeObserver(prefName, callback) {
  89. if (prefName in this.observers) {
  90. delete this.observers[prefName];
  91. }
  92. }
  93. observeBranch(listener) {}
  94. ignoreBranch(listener) {}
  95. setStringPref(prefName) {}
  96. getStringPref(prefName) { return this.get(prefName); }
  97. getBoolPref(prefName) { return this.get(prefName); }
  98. get(prefName) { return this.prefs[prefName]; }
  99. setBoolPref(prefName, value) {
  100. this.prefs[prefName] = value;
  101. if (prefName in this.observers) {
  102. this.observers[prefName]("", "", prefName);
  103. }
  104. }
  105. }
  106. FakensIPrefBranch.prototype.prefs = {};
  107. /**
  108. * Very simple fake for the most basic semantics of Preferences.jsm.
  109. * Extends FakensIPrefBranch.
  110. */
  111. export class FakePrefs extends FakensIPrefBranch {
  112. observe(prefName, callback) {
  113. super.addObserver(prefName, callback);
  114. }
  115. ignore(prefName, callback) {
  116. super.removeObserver(prefName, callback);
  117. }
  118. set(prefName, value) {
  119. this.prefs[prefName] = value;
  120. if (prefName in this.observers) {
  121. this.observers[prefName](value);
  122. }
  123. }
  124. }
  125. /**
  126. * Slimmed down version of toolkit/modules/EventEmitter.jsm
  127. */
  128. export function EventEmitter() {}
  129. EventEmitter.decorate = function(objectToDecorate) {
  130. let emitter = new EventEmitter();
  131. objectToDecorate.on = emitter.on.bind(emitter);
  132. objectToDecorate.off = emitter.off.bind(emitter);
  133. objectToDecorate.once = emitter.once.bind(emitter);
  134. objectToDecorate.emit = emitter.emit.bind(emitter);
  135. };
  136. EventEmitter.prototype = {
  137. on(event, listener) {
  138. if (!this._eventEmitterListeners) {
  139. this._eventEmitterListeners = new Map();
  140. }
  141. if (!this._eventEmitterListeners.has(event)) {
  142. this._eventEmitterListeners.set(event, []);
  143. }
  144. this._eventEmitterListeners.get(event).push(listener);
  145. },
  146. off(event, listener) {
  147. if (!this._eventEmitterListeners) {
  148. return;
  149. }
  150. let listeners = this._eventEmitterListeners.get(event);
  151. if (listeners) {
  152. this._eventEmitterListeners.set(event, listeners.filter(
  153. l => l !== listener && l._originalListener !== listener
  154. ));
  155. }
  156. },
  157. once(event, listener) {
  158. return new Promise(resolve => {
  159. let handler = (_, first, ...rest) => {
  160. this.off(event, handler);
  161. if (listener) {
  162. listener(event, first, ...rest);
  163. }
  164. resolve(first);
  165. };
  166. handler._originalListener = listener;
  167. this.on(event, handler);
  168. });
  169. },
  170. // All arguments to this method will be sent to listeners
  171. emit(event, ...args) {
  172. if (!this._eventEmitterListeners || !this._eventEmitterListeners.has(event)) {
  173. return;
  174. }
  175. let originalListeners = this._eventEmitterListeners.get(event);
  176. for (let listener of this._eventEmitterListeners.get(event)) {
  177. // If the object was destroyed during event emission, stop
  178. // emitting.
  179. if (!this._eventEmitterListeners) {
  180. break;
  181. }
  182. // If listeners were removed during emission, make sure the
  183. // event handler we're going to fire wasn't removed.
  184. if (originalListeners === this._eventEmitterListeners.get(event) ||
  185. this._eventEmitterListeners.get(event).some(l => l === listener)) {
  186. try {
  187. listener(event, ...args);
  188. } catch (ex) {
  189. // error with a listener
  190. }
  191. }
  192. }
  193. },
  194. };
  195. export function FakePerformance() {}
  196. FakePerformance.prototype = {
  197. marks: new Map(),
  198. now() {
  199. return window.performance.now();
  200. },
  201. timing: {navigationStart: 222222.123},
  202. get timeOrigin() {
  203. return 10000.234;
  204. },
  205. // XXX assumes type == "mark"
  206. getEntriesByName(name, type) {
  207. if (this.marks.has(name)) {
  208. return this.marks.get(name);
  209. }
  210. return [];
  211. },
  212. callsToMark: 0,
  213. /**
  214. * @note The "startTime" for each mark is simply the number of times mark
  215. * has been called in this object.
  216. */
  217. mark(name) {
  218. let markObj = {
  219. name,
  220. "entryType": "mark",
  221. "startTime": ++this.callsToMark,
  222. "duration": 0,
  223. };
  224. if (this.marks.has(name)) {
  225. this.marks.get(name).push(markObj);
  226. return;
  227. }
  228. this.marks.set(name, [markObj]);
  229. },
  230. };
  231. /**
  232. * addNumberReducer - a simple dummy reducer for testing that adds a number
  233. */
  234. export function addNumberReducer(prevState = 0, action) {
  235. return action.type === "ADD" ? prevState + action.data : prevState;
  236. }
  237. /**
  238. * Helper functions to test components that need IntlProvider as an ancestor
  239. */
  240. function nodeWithIntlProp(node) {
  241. return React.cloneElement(node, {intl});
  242. }
  243. export function shallowWithIntl(node, options = {}) {
  244. return shallow(nodeWithIntlProp(node), Object.assign({}, options, {context: {intl}}));
  245. }
  246. export function mountWithIntl(node, options = {}) {
  247. return mount(nodeWithIntlProp(node), Object.assign({}, options, {
  248. context: {intl},
  249. childContextTypes: {intl: intlShape},
  250. }));
  251. }