browser/components/search/test/SearchTestUtils.jsm
author Mark Banner <standard8@mozilla.com>
Thu, 12 Apr 2018 20:09:01 +0100
changeset 468188 8902ee028f5856f7be6f9827b01332763d65fbbf
child 488425 b24238e8e714ee9e8b41edc5be333d96c9a58264
permissions -rw-r--r--
Bug 1371294 - Add a SearchTestUtils.jsm file and stop duplicating promiseNewSearchEngine. r=mikedeboer MozReview-Commit-ID: IP5iRstshrM

"use strict";

ChromeUtils.import("resource://gre/modules/Services.jsm");

var EXPORTED_SYMBOLS = [
  "SearchTestUtils",
];

var gTestGlobals;

var SearchTestUtils = Object.freeze({
  init(Assert, registerCleanupFunction) {
    gTestGlobals = {
      Assert,
      registerCleanupFunction
    };
  },

  /**
   * Adds a search engine to the search service. It will remove the engine
   * at the end of the test.
   *
   * @param {String}   url                     The URL of the engine to add.
   * @param {Function} registerCleanupFunction Pass the registerCleanupFunction
   *                                           from the test's scope.
   * @returns {Promise} Returns a promise that is resolved with the new engine
   *                    or rejected if it fails.
   */
  promiseNewSearchEngine(url) {
    return new Promise((resolve, reject) => {
      Services.search.addEngine(url, null, "", false, {
        onSuccess(engine) {
          gTestGlobals.registerCleanupFunction(() => Services.search.removeEngine(engine));
          resolve(engine);
        },
        onError(errCode) {
          gTestGlobals.Assert.ok(false, `addEngine failed with error code ${errCode}`);
          reject();
        },
      });
    });
  }
});