From 991fae5d7687878eb1f18e56c56fd8ab7c980991 Mon Sep 17 00:00:00 2001 From: Alessandro Castellani Date: Thu, 21 Sep 2023 05:40:50 +0000 Subject: [PATCH] Bug 1854255 - Enable `prefer-const` as linting rule for some tests head files. r=vineet Differential Revision: https://phabricator.services.mozilla.com/D188765 --HG-- extra : moz-landing-system : lando --- .eslintrc.js | 2 + calendar/test/browser/head.js | 100 ++++----- calendar/test/unit/head.js | 48 ++-- mail/base/test/browser/head.js | 42 ++-- mail/base/test/browser/head_spacesToolbar.js | 6 +- mail/base/test/webextensions/head.js | 87 ++++---- mail/components/addrbook/test/browser/head.js | 150 ++++++------- .../components/cloudfile/test/browser/head.js | 10 +- .../enterprisepolicies/tests/browser/head.js | 12 +- .../enterprisepolicies/tests/xpcshell/head.js | 16 +- .../extensions/test/browser/head.js | 209 +++++++++--------- .../extensions/test/browser/head_menus.js | 78 +++---- .../extensions/test/xpcshell/head-imap.js | 2 +- .../extensions/test/xpcshell/head-nntp.js | 2 +- .../extensions/test/xpcshell/head.js | 52 ++--- mail/components/im/test/browser/head.js | 10 +- .../preferences/test/browser/head.js | 75 +++---- mail/test/static/head.js | 42 ++-- mailnews/addrbook/test/unit/head.js | 14 +- mailnews/addrbook/test/unit/head_cardDAV.js | 28 +-- mailnews/compose/test/unit/head_compose.js | 32 +-- .../newsblog/test/unit/head_feeds.js | 10 +- mailnews/imap/test/unit/head_server.js | 10 +- .../test/unit/head_CharsetConversionTests.js | 4 +- .../jsaccount/test/unit/head_jsaccount.js | 8 +- mailnews/local/test/unit/head_maillocal.js | 18 +- mailnews/mapi/test/unit/head_mapi.js | 34 +-- .../jsmime/test/unit/head_xpcshell_glue.js | 14 +- mailnews/mime/test/unit/head_mime.js | 10 +- mailnews/news/test/unit/head_server_setup.js | 4 +- 30 files changed, 574 insertions(+), 555 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 9d98f39b4a..88c1c1f716 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -142,6 +142,8 @@ module.exports = { vars: "local", }, ], + // Enforce using `let` only when variables are reassigned. + "prefer-const": ["error", { destructuring: "all" }], }, }, { diff --git a/calendar/test/browser/head.js b/calendar/test/browser/head.js index f76cc85754..8040c1824f 100644 --- a/calendar/test/browser/head.js +++ b/calendar/test/browser/head.js @@ -11,13 +11,13 @@ const { CalendarTestUtils } = ChromeUtils.import( ); async function openTasksTab() { - let tabmail = document.getElementById("tabmail"); - let tasksMode = tabmail.tabModes.tasks; + const tabmail = document.getElementById("tabmail"); + const tasksMode = tabmail.tabModes.tasks; if (tasksMode.tabs.length == 1) { tabmail.selectedTab = tasksMode.tabs[0]; } else { - let tasksTabButton = document.getElementById("tasksButton"); + const tasksTabButton = document.getElementById("tasksButton"); EventUtils.synthesizeMouseAtCenter(tasksTabButton, { clickCount: 1 }); } @@ -28,8 +28,8 @@ async function openTasksTab() { } async function closeTasksTab() { - let tabmail = document.getElementById("tabmail"); - let tasksMode = tabmail.tabModes.tasks; + const tabmail = document.getElementById("tabmail"); + const tasksMode = tabmail.tabModes.tasks; if (tasksMode.tabs.length == 1) { tabmail.closeTab(tasksMode.tabs[0]); @@ -56,8 +56,8 @@ async function selectFolderTab() { } async function openChatTab() { - let tabmail = document.getElementById("tabmail"); - let chatMode = tabmail.tabModes.chat; + const tabmail = document.getElementById("tabmail"); + const chatMode = tabmail.tabModes.chat; if (chatMode.tabs.length == 1) { tabmail.selectedTab = chatMode.tabs[0]; @@ -72,8 +72,8 @@ async function openChatTab() { } async function closeChatTab() { - let tabmail = document.getElementById("tabmail"); - let chatMode = tabmail.tabModes.chat; + const tabmail = document.getElementById("tabmail"); + const chatMode = tabmail.tabModes.chat; if (chatMode.tabs.length == 1) { tabmail.closeTab(chatMode.tabs[0]); @@ -91,9 +91,9 @@ async function closeChatTab() { * @returns {string} - The id of the new tab's panel element. */ async function _openNewCalendarItemTab(tabMode) { - let tabmail = document.getElementById("tabmail"); - let itemTabs = tabmail.tabModes[tabMode].tabs; - let previousTabCount = itemTabs.length; + const tabmail = document.getElementById("tabmail"); + const itemTabs = tabmail.tabModes[tabMode].tabs; + const previousTabCount = itemTabs.length; Services.prefs.setBoolPref("calendar.item.editInTab", true); let buttonId = "sidePanelNewEvent"; @@ -104,10 +104,10 @@ async function _openNewCalendarItemTab(tabMode) { await CalendarTestUtils.openCalendarTab(window); } - let newItemButton = document.getElementById(buttonId); + const newItemButton = document.getElementById(buttonId); EventUtils.synthesizeMouseAtCenter(newItemButton, { clickCount: 1 }); - let newTab = itemTabs[itemTabs.length - 1]; + const newTab = itemTabs[itemTabs.length - 1]; is(itemTabs.length, previousTabCount + 1, `new ${tabMode} tab is open`); is(tabmail.selectedTab, newTab, `new ${tabMode} tab is selected`); @@ -117,8 +117,8 @@ async function _openNewCalendarItemTab(tabMode) { return newTab.panel.id; } -let openNewCalendarEventTab = _openNewCalendarItemTab.bind(null, "calendarEvent"); -let openNewCalendarTaskTab = _openNewCalendarItemTab.bind(null, "calendarTask"); +const openNewCalendarEventTab = _openNewCalendarItemTab.bind(null, "calendarEvent"); +const openNewCalendarTaskTab = _openNewCalendarItemTab.bind(null, "calendarTask"); /** * Selects an existing (open) calendar event or task tab. @@ -127,9 +127,9 @@ let openNewCalendarTaskTab = _openNewCalendarItemTab.bind(null, "calendarTask"); * @param {string} panelId - The id of the tab's panel element. */ async function _selectCalendarItemTab(tabMode, panelId) { - let tabmail = document.getElementById("tabmail"); - let itemTabs = tabmail.tabModes[tabMode].tabs; - let tabToSelect = itemTabs.find(tab => tab.panel.id == panelId); + const tabmail = document.getElementById("tabmail"); + const itemTabs = tabmail.tabModes[tabMode].tabs; + const tabToSelect = itemTabs.find(tab => tab.panel.id == panelId); ok(tabToSelect, `${tabMode} tab is open`); @@ -140,8 +140,8 @@ async function _selectCalendarItemTab(tabMode, panelId) { await new Promise(resolve => setTimeout(resolve)); } -let selectCalendarEventTab = _selectCalendarItemTab.bind(null, "calendarEvent"); -let selectCalendarTaskTab = _selectCalendarItemTab.bind(null, "calendarTask"); +const selectCalendarEventTab = _selectCalendarItemTab.bind(null, "calendarEvent"); +const selectCalendarTaskTab = _selectCalendarItemTab.bind(null, "calendarTask"); /** * Closes a calendar event or task tab. @@ -150,14 +150,14 @@ let selectCalendarTaskTab = _selectCalendarItemTab.bind(null, "calendarTask"); * @param {string} panelId - The id of the panel of the tab to close. */ async function _closeCalendarItemTab(tabMode, panelId) { - let tabmail = document.getElementById("tabmail"); - let itemTabs = tabmail.tabModes[tabMode].tabs; - let previousTabCount = itemTabs.length; - let itemTab = itemTabs.find(tab => tab.panel.id == panelId); + const tabmail = document.getElementById("tabmail"); + const itemTabs = tabmail.tabModes[tabMode].tabs; + const previousTabCount = itemTabs.length; + const itemTab = itemTabs.find(tab => tab.panel.id == panelId); if (itemTab) { // Tab does not immediately close, so wait for it. - let tabClosedPromise = new Promise(resolve => { + const tabClosedPromise = new Promise(resolve => { itemTab.tabNode.addEventListener("TabClose", resolve, { once: true }); }); tabmail.closeTab(itemTab); @@ -169,8 +169,8 @@ async function _closeCalendarItemTab(tabMode, panelId) { await new Promise(resolve => setTimeout(resolve)); } -let closeCalendarEventTab = _closeCalendarItemTab.bind(null, "calendarEvent"); -let closeCalendarTaskTab = _closeCalendarItemTab.bind(null, "calendarTask"); +const closeCalendarEventTab = _closeCalendarItemTab.bind(null, "calendarEvent"); +const closeCalendarTaskTab = _closeCalendarItemTab.bind(null, "calendarTask"); async function openPreferencesTab() { const tabmail = document.getElementById("tabmail"); @@ -189,8 +189,8 @@ async function openPreferencesTab() { } async function closeAddressBookTab() { - let tabmail = document.getElementById("tabmail"); - let abMode = tabmail.tabModes.addressBookTab; + const tabmail = document.getElementById("tabmail"); + const abMode = tabmail.tabModes.addressBookTab; if (abMode.tabs.length == 1) { tabmail.closeTab(abMode.tabs[0]); @@ -202,8 +202,8 @@ async function closeAddressBookTab() { } async function closePreferencesTab() { - let tabmail = document.getElementById("tabmail"); - let prefsMode = tabmail.tabModes.preferencesTab; + const tabmail = document.getElementById("tabmail"); + const prefsMode = tabmail.tabModes.preferencesTab; if (prefsMode.tabs.length == 1) { tabmail.closeTab(prefsMode.tabs[0]); @@ -231,8 +231,8 @@ async function openAddonsTab() { } async function closeAddonsTab() { - let tabmail = document.getElementById("tabmail"); - let contentMode = tabmail.tabModes.contentTab; + const tabmail = document.getElementById("tabmail"); + const contentMode = tabmail.tabModes.contentTab; if (contentMode.tabs.length == 1) { tabmail.closeTab(contentMode.tabs[0]); @@ -261,9 +261,9 @@ async function createCalendarUsingDialog(name, data = {}) { * @param {nsIDOMWindow} win - The dialog window. */ async function useDialog(win) { - let doc = win.document; - let dialogElement = doc.querySelector("dialog"); - let acceptButton = dialogElement.getButton("accept"); + const doc = win.document; + const dialogElement = doc.querySelector("dialog"); + const acceptButton = dialogElement.getButton("accept"); if (data.network) { // Choose network calendar type. @@ -272,9 +272,9 @@ async function createCalendarUsingDialog(name, data = {}) { // Enter a location. if (data.network.location == undefined) { - let calendarFile = Services.dirsvc.get("TmpD", Ci.nsIFile); + const calendarFile = Services.dirsvc.get("TmpD", Ci.nsIFile); calendarFile.append(name + ".ics"); - let fileURI = Services.io.newFileURI(calendarFile); + const fileURI = Services.io.newFileURI(calendarFile); data.network.location = fileURI.prePath + fileURI.pathQueryRef; } EventUtils.synthesizeMouseAtCenter(doc.querySelector("#network-location-input"), {}, win); @@ -284,7 +284,7 @@ async function createCalendarUsingDialog(name, data = {}) { if (data.network.offline == undefined) { data.network.offline = true; } - let offlineCheckbox = doc.querySelector("#network-cache-checkbox"); + const offlineCheckbox = doc.querySelector("#network-cache-checkbox"); if (!offlineCheckbox.checked) { EventUtils.synthesizeMouseAtCenter(offlineCheckbox, {}, win); } @@ -292,7 +292,7 @@ async function createCalendarUsingDialog(name, data = {}) { // Set up an observer to wait for calendar(s) to be found, before // clicking the accept button to subscribe to the calendar(s). - let observer = new MutationObserver(mutationList => { + const observer = new MutationObserver(mutationList => { mutationList.forEach(async mutation => { if (mutation.type === "childList") { acceptButton.click(); @@ -308,7 +308,7 @@ async function createCalendarUsingDialog(name, data = {}) { // Set calendar name. // Setting the value does not activate the accept button on all platforms, // so we need to type something in case the field is empty. - let nameInput = doc.querySelector("#local-calendar-name-input"); + const nameInput = doc.querySelector("#local-calendar-name-input"); if (nameInput.value == "") { EventUtils.synthesizeMouseAtCenter(nameInput, {}, win); EventUtils.sendString(name, win); @@ -318,7 +318,7 @@ async function createCalendarUsingDialog(name, data = {}) { if (data.showReminders == undefined) { data.showReminders = true; } - let localFireAlarmsCheckbox = doc.querySelector("#local-fire-alarms-checkbox"); + const localFireAlarmsCheckbox = doc.querySelector("#local-fire-alarms-checkbox"); if (localFireAlarmsCheckbox.checked != data.showReminders) { EventUtils.synthesizeMouseAtCenter(localFireAlarmsCheckbox, {}, win); } @@ -327,7 +327,7 @@ async function createCalendarUsingDialog(name, data = {}) { if (data.email == undefined) { data.email = "none"; } - let emailIdentityMenulist = doc.querySelector("#email-identity-menulist"); + const emailIdentityMenulist = doc.querySelector("#email-identity-menulist"); EventUtils.synthesizeMouseAtCenter(emailIdentityMenulist, {}, win); emailIdentityMenulist.querySelector("menuitem[value='none']").click(); @@ -336,7 +336,7 @@ async function createCalendarUsingDialog(name, data = {}) { } } - let dialogWindowPromise = BrowserTestUtils.promiseAlertDialog( + const dialogWindowPromise = BrowserTestUtils.promiseAlertDialog( null, "chrome://calendar/content/calendar-creation.xhtml", { callback: useDialog } @@ -359,13 +359,13 @@ registerCleanupFunction(async () => { await closeAddonsTab(); // Close any event or task tabs that are open. - let tabmail = document.getElementById("tabmail"); - let eventTabPanelIds = tabmail.tabModes.calendarEvent.tabs.map(tab => tab.panel.id); - let taskTabPanelIds = tabmail.tabModes.calendarTask.tabs.map(tab => tab.panel.id); - for (let id of eventTabPanelIds) { + const tabmail = document.getElementById("tabmail"); + const eventTabPanelIds = tabmail.tabModes.calendarEvent.tabs.map(tab => tab.panel.id); + const taskTabPanelIds = tabmail.tabModes.calendarTask.tabs.map(tab => tab.panel.id); + for (const id of eventTabPanelIds) { await closeCalendarEventTab(id); } - for (let id of taskTabPanelIds) { + for (const id of taskTabPanelIds) { await closeCalendarTaskTab(id); } Services.prefs.setBoolPref("calendar.item.editInTab", false); diff --git a/calendar/test/unit/head.js b/calendar/test/unit/head.js index 24e6f7756c..cbfde8ab26 100644 --- a/calendar/test/unit/head.js +++ b/calendar/test/unit/head.js @@ -14,7 +14,7 @@ updateAppInfo(); var { cal } = ChromeUtils.importESModule("resource:///modules/calendar/calUtils.sys.mjs"); function createDate(aYear, aMonth, aDay, aHasTime, aHour, aMinute, aSecond, aTimezone) { - let date = Cc["@mozilla.org/calendar/datetime;1"].createInstance(Ci.calIDateTime); + const date = Cc["@mozilla.org/calendar/datetime;1"].createInstance(Ci.calIDateTime); date.resetTo( aYear, aMonth, @@ -30,19 +30,19 @@ function createDate(aYear, aMonth, aDay, aHasTime, aHour, aMinute, aSecond, aTim function createEventFromIcalString(icalString) { if (/^BEGIN:VCALENDAR/.test(icalString)) { - let parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); + const parser = Cc["@mozilla.org/calendar/ics-parser;1"].createInstance(Ci.calIIcsParser); parser.parseString(icalString); - let items = parser.getItems(); + const items = parser.getItems(); cal.ASSERT(items.length == 1); return items[0].QueryInterface(Ci.calIEvent); } - let event = Cc["@mozilla.org/calendar/event;1"].createInstance(Ci.calIEvent); + const event = Cc["@mozilla.org/calendar/event;1"].createInstance(Ci.calIEvent); event.icalString = icalString; return event; } function createTodoFromIcalString(icalString) { - let todo = Cc["@mozilla.org/calendar/todo;1"].createInstance(Ci.calITodo); + const todo = Cc["@mozilla.org/calendar/todo;1"].createInstance(Ci.calITodo); todo.icalString = icalString; return todo; } @@ -59,15 +59,15 @@ function getStorageCal() { do_get_profile(); // create URI - let db = Services.dirsvc.get("TmpD", Ci.nsIFile); + const db = Services.dirsvc.get("TmpD", Ci.nsIFile); db.append("test_storage.sqlite"); - let uri = Services.io.newFileURI(db); + const uri = Services.io.newFileURI(db); // Make sure timezone service is initialized Cc["@mozilla.org/calendar/timezone-service;1"].getService(Ci.calIStartupService).startup(null); // create storage calendar - let stor = Cc["@mozilla.org/calendar/calendar;1?type=storage"].createInstance( + const stor = Cc["@mozilla.org/calendar/calendar;1?type=storage"].createInstance( Ci.calISyncWriteCalendar ); stor.uri = uri; @@ -195,19 +195,19 @@ function ics_unfoldline(aLine) { * @returns The interpolated, dedented string */ function dedent(strings, ...values) { - let parts = []; + const parts = []; // Perform variable interpolation let minIndent = Infinity; - for (let [i, string] of strings.entries()) { - let innerparts = string.split("\n"); + for (const [i, string] of strings.entries()) { + const innerparts = string.split("\n"); if (i == 0) { innerparts.shift(); } if (i == strings.length - 1) { innerparts.pop(); } - for (let [j, ip] of innerparts.entries()) { - let match = ip.match(/^(\s*)\S*/); + for (const [j, ip] of innerparts.entries()) { + const match = ip.match(/^(\s*)\S*/); if (j != 0) { minIndent = Math.min(minIndent, match[1].length); } @@ -232,11 +232,13 @@ function dedent(strings, ...values) { * Read a JSON file and return the JS object */ function readJSONFile(aFile) { - let stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream); + const stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); try { stream.init(aFile, FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0); - let bytes = NetUtil.readInputStream(stream, stream.available()); - let data = JSON.parse(new TextDecoder().decode(bytes)); + const bytes = NetUtil.readInputStream(stream, stream.available()); + const data = JSON.parse(new TextDecoder().decode(bytes)); return data; } catch (ex) { dump("readJSONFile: Error reading JSON file: " + ex); @@ -267,7 +269,7 @@ function do_load_calmgr(callback) { } function do_calendar_startup(callback) { - let obs = { + const obs = { observe() { Services.obs.removeObserver(this, "calendar-startup-done"); do_test_finished(); @@ -275,7 +277,7 @@ function do_calendar_startup(callback) { }, }; - let startupService = Cc["@mozilla.org/calendar/startup-service;1"].getService( + const startupService = Cc["@mozilla.org/calendar/startup-service;1"].getService( Ci.nsISupports ).wrappedJSObject; @@ -302,10 +304,10 @@ function do_calendar_startup(callback) { * @param func The function to monkey patch with. */ function monkeyPatch(obj, x, func) { - let old = obj[x]; + const old = obj[x]; obj[x] = function () { - let parent = old.bind(obj); - let args = Array.from(arguments); + const parent = old.bind(obj); + const args = Array.from(arguments); args.unshift(parent); try { return func.apply(obj, args); @@ -325,8 +327,8 @@ function monkeyPatch(obj, x, func) { * @param {string} level - The variable name to refer to report on. */ function compareExtractResults(actual, expected, level = "") { - for (let [key, value] of Object.entries(expected)) { - let qualifiedKey = [level, Array.isArray(expected) ? `[${key}]` : `.${key}`].join(""); + for (const [key, value] of Object.entries(expected)) { + const qualifiedKey = [level, Array.isArray(expected) ? `[${key}]` : `.${key}`].join(""); if (value && typeof value == "object") { Assert.ok(actual[key], `${qualifiedKey} is not null`); compareExtractResults(actual[key], value, qualifiedKey); diff --git a/mail/base/test/browser/head.js b/mail/base/test/browser/head.js index 255f00a834..a239f4f918 100644 --- a/mail/base/test/browser/head.js +++ b/mail/base/test/browser/head.js @@ -17,7 +17,7 @@ async function focusWindow(win) { async function openExtensionPopup(win, buttonId) { await focusWindow(win.top); - let actionButton = await TestUtils.waitForCondition( + const actionButton = await TestUtils.waitForCondition( () => win.document.querySelector( `#${buttonId}, [item-id="${buttonId}"] button` @@ -30,10 +30,10 @@ async function openExtensionPopup(win, buttonId) { ); EventUtils.synthesizeMouseAtCenter(actionButton, {}, win); - let panel = win.top.document.getElementById( + const panel = win.top.document.getElementById( "webextension-remote-preload-panel" ); - let browser = panel.querySelector("browser"); + const browser = panel.querySelector("browser"); await TestUtils.waitForCondition( () => browser.clientWidth > 100, "waiting for browser to resize" @@ -47,10 +47,10 @@ function getSmartServer() { } function resetSmartMailboxes() { - let oldServer = getSmartServer(); + const oldServer = getSmartServer(); // Clean up any leftover server from an earlier test. if (oldServer) { - let oldAccount = MailServices.accounts.FindAccountForServer(oldServer); + const oldAccount = MailServices.accounts.FindAccountForServer(oldServer); MailServices.accounts.removeAccount(oldAccount, false); } } @@ -96,7 +96,7 @@ class MenuTestHelper { * Clicks on the menu and waits for it to open. */ async openMenu() { - let shownPromise = BrowserTestUtils.waitForEvent( + const shownPromise = BrowserTestUtils.waitForEvent( this.menu.menupopup, "popupshown" ); @@ -137,7 +137,7 @@ class MenuTestHelper { ); } if (expected.l10nID) { - let attributes = actual.ownerDocument.l10n.getAttributes(actual); + const attributes = actual.ownerDocument.l10n.getAttributes(actual); Assert.equal(attributes.id, expected.l10nID, `${actual.id} L10n string`); Assert.deepEqual( attributes.args, @@ -161,7 +161,7 @@ class MenuTestHelper { await BrowserTestUtils.waitForEvent(popup, "popupshown"); } - for (let item of popup.children) { + for (const item of popup.children) { if (!item.id || item.localName == "menuseparator") { continue; } @@ -172,7 +172,7 @@ class MenuTestHelper { } continue; } - let itemData = data[item.id]; + const itemData = data[item.id]; this.checkItem(item, itemData); delete data[item.id]; @@ -181,7 +181,7 @@ class MenuTestHelper { item.openMenu(true); await this.iterate(item.menupopup, data, itemsMustBeInData); } else { - for (let hiddenItem of item.querySelectorAll("menu, menuitem")) { + for (const hiddenItem of item.querySelectorAll("menu, menuitem")) { delete data[hiddenItem.id]; } } @@ -200,8 +200,8 @@ class MenuTestHelper { */ async testAllItems(mode) { // Get the data for just this mode. - let data = {}; - for (let [id, itemData] of Object.entries(this.baseData)) { + const data = {}; + for (const [id, itemData] of Object.entries(this.baseData)) { data[id] = { ...itemData, hidden: itemData.hidden === true || itemData.hidden?.includes(mode), @@ -216,7 +216,7 @@ class MenuTestHelper { await this.iterate(this.menu.menupopup, data, true); // Report any unexpected items. - for (let id of Object.keys(data)) { + for (const id of Object.keys(data)) { Assert.report(true, undefined, undefined, `extra item ${id} in data`); } } @@ -230,12 +230,12 @@ class MenuTestHelper { await this.openMenu(); await this.iterate(this.menu.menupopup, data); - for (let id of Object.keys(data)) { + for (const id of Object.keys(data)) { Assert.report(true, undefined, undefined, `extra item ${id} in data`); } if (this.menu.menupopup.state != "closed") { - let hiddenPromise = BrowserTestUtils.waitForEvent( + const hiddenPromise = BrowserTestUtils.waitForEvent( this.menu.menupopup, "popuphidden" ); @@ -255,11 +255,11 @@ class MenuTestHelper { */ async activateItem(menuItemID, data) { await this.openMenu(); - let hiddenPromise = BrowserTestUtils.waitForEvent( + const hiddenPromise = BrowserTestUtils.waitForEvent( this.menu.menupopup, "popuphidden" ); - let item = document.getElementById(menuItemID); + const item = document.getElementById(menuItemID); if (data) { this.checkItem(item, data); } @@ -326,7 +326,7 @@ registerCleanupFunction(function () { "view" ); - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); if (tabmail.tabInfo.length > 1) { Assert.report( true, @@ -337,7 +337,7 @@ registerCleanupFunction(function () { tabmail.closeOtherTabs(0); } - for (let server of MailServices.accounts.allServers) { + for (const server of MailServices.accounts.allServers) { Assert.report( true, undefined, @@ -346,7 +346,7 @@ registerCleanupFunction(function () { ); MailServices.accounts.removeIncomingServer(server, false); } - for (let account of MailServices.accounts.accounts) { + for (const account of MailServices.accounts.accounts) { Assert.report( true, undefined, @@ -363,7 +363,7 @@ registerCleanupFunction(function () { Services.focus.focusedWindow = window; // Focus an element in the main window, then blur it again to avoid it // hijacking keypresses. - let mainWindowElement = document.getElementById("button-appmenu"); + const mainWindowElement = document.getElementById("button-appmenu"); mainWindowElement.focus(); mainWindowElement.blur(); }); diff --git a/mail/base/test/browser/head_spacesToolbar.js b/mail/base/test/browser/head_spacesToolbar.js index f08f3deee5..624a683fa0 100644 --- a/mail/base/test/browser/head_spacesToolbar.js +++ b/mail/base/test/browser/head_spacesToolbar.js @@ -3,8 +3,8 @@ * file, you can obtain one at http://mozilla.org/MPL/2.0/. */ async function sub_test_toolbar_alignment(drawInTitlebar, hideMenu) { - let menubar = document.getElementById("toolbar-menubar"); - let tabsInTitlebar = + const menubar = document.getElementById("toolbar-menubar"); + const tabsInTitlebar = document.documentElement.getAttribute("tabsintitlebar") == "true"; Assert.equal(tabsInTitlebar, drawInTitlebar); @@ -17,7 +17,7 @@ async function sub_test_toolbar_alignment(drawInTitlebar, hideMenu) { } await new Promise(resolve => requestAnimationFrame(resolve)); - let size = document + const size = document .getElementById("spacesToolbar") .getBoundingClientRect().width; diff --git a/mail/base/test/webextensions/head.js b/mail/base/test/webextensions/head.js index 28019fdaf6..da2397babc 100644 --- a/mail/base/test/webextensions/head.js +++ b/mail/base/test/webextensions/head.js @@ -22,7 +22,7 @@ const l10n = new Localization([ var { CustomizableUITestUtils } = ChromeUtils.import( "resource://testing-common/CustomizableUITestUtils.jsm" ); -let gCUITestUtils = new CustomizableUITestUtils(window); +const gCUITestUtils = new CustomizableUITestUtils(window); const { PermissionTestUtils } = ChromeUtils.import( "resource://testing-common/PermissionTestUtils.jsm" @@ -40,7 +40,7 @@ const { PermissionTestUtils } = ChromeUtils.import( function promisePopupNotificationShown(name) { return new Promise(resolve => { function popupshown() { - let notification = PopupNotifications.getNotification(name); + const notification = PopupNotifications.getNotification(name); if (!notification) { return; } @@ -70,7 +70,7 @@ function promisePopupNotificationShown(name) { */ function promiseInstallEvent(addon, event) { return new Promise(resolve => { - let listener = {}; + const listener = {}; listener[event] = (install, arg) => { if (install.addon.id == addon.id) { AddonManager.removeInstallListener(listener); @@ -94,10 +94,10 @@ function promiseInstallEvent(addon, event) { * object as the resolution value. */ async function promiseInstallAddon(url, telemetryInfo) { - let install = await AddonManager.getInstallForURL(url, { telemetryInfo }); + const install = await AddonManager.getInstallForURL(url, { telemetryInfo }); install.install(); - let addon = await new Promise(resolve => { + const addon = await new Promise(resolve => { install.addListener({ onInstallEnded(_install, _addon) { resolve(_addon); @@ -132,8 +132,8 @@ async function promiseInstallAddon(url, telemetryInfo) { * Resolves when the extension has ben updated. */ async function waitForUpdate(addon) { - let installPromise = promiseInstallEvent(addon, "onInstallEnded"); - let readyPromise = new Promise(resolve => { + const installPromise = promiseInstallEvent(addon, "onInstallEnded"); + const readyPromise = new Promise(resolve => { function listener(event, extension) { if (extension.id == addon.id) { Management.off("ready", listener); @@ -143,7 +143,7 @@ async function waitForUpdate(addon) { Management.on("ready", listener); }); - let [newAddon] = await Promise.all([installPromise, readyPromise]); + const [newAddon] = await Promise.all([installPromise, readyPromise]); return newAddon; } @@ -196,13 +196,15 @@ async function checkNotification( sideloaded, warning = false ) { - let icon = panel.getAttribute("icon"); - let ul = document.getElementById("addon-webext-perm-list"); - let singleDataEl = document.getElementById("addon-webext-perm-single-entry"); - let experimentWarning = document.getElementById( + const icon = panel.getAttribute("icon"); + const ul = document.getElementById("addon-webext-perm-list"); + const singleDataEl = document.getElementById( + "addon-webext-perm-single-entry" + ); + const experimentWarning = document.getElementById( "addon-webext-experiment-warning" ); - let learnMoreLink = document.getElementById("addon-webext-perm-info"); + const learnMoreLink = document.getElementById("addon-webext-perm-info"); if (checkIcon instanceof RegExp) { ok( @@ -270,18 +272,18 @@ async function testInstallMethod(installFn) { ], }); - let testURI = makeURI("https://example.com/"); + const testURI = makeURI("https://example.com/"); PermissionTestUtils.add(testURI, "install", Services.perms.ALLOW_ACTION); registerCleanupFunction(() => PermissionTestUtils.remove(testURI, "install")); async function runOnce(filename, cancel) { - let tab = openContentTab("about:blank"); + const tab = openContentTab("about:blank"); if (tab.browser.webProgress.isLoadingDocument) { await BrowserTestUtils.browserLoaded(tab.browser); } - let installPromise = new Promise(resolve => { - let listener = { + const installPromise = new Promise(resolve => { + const listener = { onDownloadCancelled() { AddonManager.removeInstallListener(listener); resolve(false); @@ -310,7 +312,7 @@ async function testInstallMethod(installFn) { AddonManager.addInstallListener(listener); }); - let installMethodPromise = installFn(filename); + const installMethodPromise = installFn(filename); let panel = await promisePopupNotificationShown("addon-webext-permissions"); if (filename == PERMS_XPI) { @@ -337,7 +339,8 @@ async function testInstallMethod(installFn) { } catch (err) {} } else { // Look for post-install notification - let postInstallPromise = promisePopupNotificationShown("addon-installed"); + const postInstallPromise = + promisePopupNotificationShown("addon-installed"); panel.button.click(); // Press OK on the post-install notification @@ -347,8 +350,8 @@ async function testInstallMethod(installFn) { await installMethodPromise; } - let result = await installPromise; - let addon = await AddonManager.getAddonByID(ID); + const result = await installPromise; + const addon = await AddonManager.getAddonByID(ID); if (cancel) { ok(!result, "Installation was cancelled"); is(addon, null, "Extension is not installed"); @@ -358,7 +361,7 @@ async function testInstallMethod(installFn) { await addon.uninstall(); } - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); tabmail.closeOtherTabs(tabmail.tabInfo[0]); } @@ -409,7 +412,7 @@ async function interactiveUpdateTest(autoUpdate, checkFn) { let manualUpdatePromise; if (!autoUpdate) { manualUpdatePromise = new Promise(resolve => { - let listener = { + const listener = { onNewInstall() { AddonManager.removeInstallListener(listener); resolve(); @@ -419,25 +422,29 @@ async function interactiveUpdateTest(autoUpdate, checkFn) { }); } - let promise = checkFn(win, addon); + const promise = checkFn(win, addon); if (manualUpdatePromise) { await manualUpdatePromise; - let doc = win.document; + const doc = win.document; if (win.gViewController.currentViewId !== "addons://updates/available") { - let showUpdatesBtn = doc.querySelector("addon-updates-message").button; + const showUpdatesBtn = doc.querySelector( + "addon-updates-message" + ).button; await TestUtils.waitForCondition(() => { return !showUpdatesBtn.hidden; }, "Wait for show updates button"); - let viewChanged = waitAboutAddonsViewLoaded(doc); + const viewChanged = waitAboutAddonsViewLoaded(doc); showUpdatesBtn.click(); await viewChanged; } - let card = await TestUtils.waitForCondition(() => { + const card = await TestUtils.waitForCondition(() => { return doc.querySelector(`addon-card[addon-id="${ID}"]`); }, `Wait addon card for "${ID}"`); - let updateBtn = card.querySelector('panel-item[action="install-update"]'); + const updateBtn = card.querySelector( + 'panel-item[action="install-update"]' + ); ok(updateBtn, `Found update button for "${ID}"`); updateBtn.click(); } @@ -455,7 +462,7 @@ async function interactiveUpdateTest(autoUpdate, checkFn) { ok(addon, "Addon was installed"); is(addon.version, "1.0", "Version 1 of the addon is installed"); - let win = await openAddonsMgr("addons://list/extension"); + const win = await openAddonsMgr("addons://list/extension"); await waitAboutAddonsViewLoaded(win.document); @@ -465,7 +472,7 @@ async function interactiveUpdateTest(autoUpdate, checkFn) { let panel = await popupPromise; // Click the cancel button, wait to see the cancel event - let cancelPromise = promiseInstallEvent(addon, "onInstallCancelled"); + const cancelPromise = promiseInstallEvent(addon, "onInstallCancelled"); panel.secondaryButton.click(); await cancelPromise; @@ -480,7 +487,7 @@ async function interactiveUpdateTest(autoUpdate, checkFn) { checkPromise = (await triggerUpdate(win, addon)).promise; // This time, accept the upgrade - let updatePromise = waitForUpdate(addon); + const updatePromise = waitForUpdate(addon); panel = await popupPromise; panel.button.click(); @@ -489,7 +496,7 @@ async function interactiveUpdateTest(autoUpdate, checkFn) { await checkPromise; - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); tabmail.closeTab(tabmail.currentTabInfo); await addon.uninstall(); await SpecialPowers.popPrefEnv(); @@ -536,7 +543,7 @@ async function interactiveUpdateTest(autoUpdate, checkFn) { "Every update telemetry event should have the update_from extra var 'user'" ); - let hasPermissionsExtras = collectedUpdateEvents + const hasPermissionsExtras = collectedUpdateEvents .filter(evt => { return evt.extra.step === "permissions_prompt"; }) @@ -549,7 +556,7 @@ async function interactiveUpdateTest(autoUpdate, checkFn) { "Every 'permissions_prompt' update telemetry event should have the permissions extra vars" ); - let hasDownloadTimeExtras = collectedUpdateEvents + const hasDownloadTimeExtras = collectedUpdateEvents .filter(evt => { return evt.extra.step === "download_completed"; }) @@ -575,8 +582,8 @@ async function interactiveUpdateTest(autoUpdate, checkFn) { // to ensure it gets called before the final check is performed. let testCleanup; add_task(async function () { - let addons = await AddonManager.getAllAddons(); - let existingAddons = new Set(addons.map(a => a.id)); + const addons = await AddonManager.getAllAddons(); + const existingAddons = new Set(addons.map(a => a.id)); registerCleanupFunction(async function () { if (testCleanup) { @@ -584,7 +591,7 @@ add_task(async function () { testCleanup = null; } - for (let addon of await AddonManager.getAllAddons()) { + for (const addon of await AddonManager.getAllAddons()) { // Builtin search extensions may have been installed by SearchService // during the test run, ignore those. if ( @@ -606,14 +613,14 @@ registerCleanupFunction(() => { ok(PanelUI.panel.state == "closed", "Main menu is closed."); // Any opened tabs should be closed by the end of the test. - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); is(tabmail.tabInfo.length, 1, "All tabs are closed."); tabmail.closeOtherTabs(0); }); let collectedTelemetry = []; function hookExtensionsTelemetry() { - let originalHistogram = ExtensionsUI.histogram; + const originalHistogram = ExtensionsUI.histogram; ExtensionsUI.histogram = { add(value) { collectedTelemetry.push(value); diff --git a/mail/components/addrbook/test/browser/head.js b/mail/components/addrbook/test/browser/head.js index 75c3ec0f0b..8bdf038c4f 100644 --- a/mail/components/addrbook/test/browser/head.js +++ b/mail/components/addrbook/test/browser/head.js @@ -29,7 +29,7 @@ registerCleanupFunction(function () { 2, "Only Personal ab and Collected Addresses should be left." ); - for (let directory of MailServices.ab.directories) { + for (const directory of MailServices.ab.directories) { if ( directory.dirPrefId == "ldap_2.servers.history" || directory.dirPrefId == "ldap_2.servers.pab" @@ -57,7 +57,7 @@ registerCleanupFunction(function () { Services.focus.focusedWindow = window; // Focus an element in the main window, then blur it again to avoid it // hijacking keypresses. - let mainWindowElement = document.getElementById("button-appmenu"); + const mainWindowElement = document.getElementById("button-appmenu"); mainWindowElement.focus(); mainWindowElement.blur(); // Reset the window to its default size. @@ -76,27 +76,27 @@ async function openAddressBookWindow() { } function closeAddressBookWindow() { - let abTab = getAddressBookTab(); + const abTab = getAddressBookTab(); if (abTab) { - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); tabmail.closeTab(abTab); } } function getAddressBookTab() { - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); return tabmail.tabInfo.find( t => t.browser?.currentURI.spec == "about:addressbook" ); } function getAddressBookWindow() { - let tab = getAddressBookTab(); + const tab = getAddressBookTab(); return tab?.browser.contentWindow; } async function openAllAddressBooks() { - let abWindow = getAddressBookWindow(); + const abWindow = getAddressBookWindow(); EventUtils.synthesizeMouseAtCenter( abWindow.document.querySelector("#books > li"), {}, @@ -106,33 +106,33 @@ async function openAllAddressBooks() { } function openDirectory(directory) { - let abWindow = getAddressBookWindow(); - let row = abWindow.booksList.getRowForUID(directory.UID); + const abWindow = getAddressBookWindow(); + const row = abWindow.booksList.getRowForUID(directory.UID); EventUtils.synthesizeMouseAtCenter(row.querySelector("span"), {}, abWindow); } function createAddressBook(dirName, type = Ci.nsIAbManager.JS_DIRECTORY_TYPE) { - let prefName = MailServices.ab.newAddressBook(dirName, null, type); + const prefName = MailServices.ab.newAddressBook(dirName, null, type); return MailServices.ab.getDirectoryFromId(prefName); } async function createAddressBookWithUI(abName) { - let newAddressBookPromise = promiseLoadSubDialog( + const newAddressBookPromise = promiseLoadSubDialog( "chrome://messenger/content/addressbook/abAddressBookNameDialog.xhtml" ); - let abWindow = getAddressBookWindow(); + const abWindow = getAddressBookWindow(); EventUtils.synthesizeMouseAtCenter( abWindow.document.getElementById("toolbarCreateBook"), {}, abWindow ); - let abNameDialog = await newAddressBookPromise; + const abNameDialog = await newAddressBookPromise; EventUtils.sendString(abName, abNameDialog); abNameDialog.document.querySelector("dialog").getButton("accept").click(); - let addressBook = MailServices.ab.directories.find( + const addressBook = MailServices.ab.directories.find( directory => directory.dirName == abName ); @@ -145,7 +145,7 @@ async function createAddressBookWithUI(abName) { } function createContact(firstName, lastName, displayName, primaryEmail) { - let contact = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance( + const contact = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance( Ci.nsIAbCard ); contact.displayName = displayName ?? `${firstName} ${lastName}`; @@ -157,9 +157,9 @@ function createContact(firstName, lastName, displayName, primaryEmail) { } function createMailingList(name) { - let list = Cc["@mozilla.org/addressbook/directoryproperty;1"].createInstance( - Ci.nsIAbDirectory - ); + const list = Cc[ + "@mozilla.org/addressbook/directoryproperty;1" + ].createInstance(Ci.nsIAbDirectory); list.isMailList = true; list.dirName = name; return list; @@ -168,26 +168,26 @@ function createMailingList(name) { async function createMailingListWithUI(mlParent, mlName) { openDirectory(mlParent); - let newAddressBookPromise = promiseLoadSubDialog( + const newAddressBookPromise = promiseLoadSubDialog( "chrome://messenger/content/addressbook/abMailListDialog.xhtml" ); - let abWindow = getAddressBookWindow(); + const abWindow = getAddressBookWindow(); EventUtils.synthesizeMouseAtCenter( abWindow.document.getElementById("toolbarCreateList"), {}, abWindow ); - let abListDialog = await newAddressBookPromise; - let abListDocument = abListDialog.document; + const abListDialog = await newAddressBookPromise; + const abListDocument = abListDialog.document; await new Promise(resolve => abListDialog.setTimeout(resolve)); abListDocument.getElementById("abPopup").value = mlParent.URI; abListDocument.getElementById("ListName").value = mlName; abListDocument.querySelector("dialog").getButton("accept").click(); - let list = mlParent.childNodes.find(list => list.dirName == mlName); + const list = mlParent.childNodes.find(list => list.dirName == mlName); Assert.ok(list, "a new list was created"); @@ -198,9 +198,9 @@ async function createMailingListWithUI(mlParent, mlName) { } function checkDirectoryDisplayed(directory) { - let abWindow = getAddressBookWindow(); - let booksList = abWindow.document.getElementById("books"); - let cardsList = abWindow.cardsPane.cardsList; + const abWindow = getAddressBookWindow(); + const booksList = abWindow.document.getElementById("books"); + const cardsList = abWindow.cardsPane.cardsList; if (directory) { Assert.equal( @@ -221,10 +221,10 @@ function checkCardsListed(...expectedCards) { ) ); - let abWindow = getAddressBookWindow(); - let cardsList = abWindow.document.getElementById("cards"); + const abWindow = getAddressBookWindow(); + const cardsList = abWindow.document.getElementById("cards"); for (let i = 0; i < expectedCards.length; i++) { - let row = cardsList.getRowAtIndex(i); + const row = cardsList.getRowAtIndex(i); Assert.equal( row.classList.contains("MailList"), expectedCards[i].isMailList, @@ -246,9 +246,9 @@ function checkCardsListed(...expectedCards) { } function checkNamesListed(...expectedNames) { - let abWindow = getAddressBookWindow(); - let cardsList = abWindow.document.getElementById("cards"); - let expectedCount = expectedNames.length; + const abWindow = getAddressBookWindow(); + const cardsList = abWindow.document.getElementById("cards"); + const expectedCount = expectedNames.length; Assert.equal( cardsList.view.rowCount, @@ -272,8 +272,8 @@ function checkNamesListed(...expectedNames) { } function checkPlaceholders(expectedVisible = []) { - let abWindow = getAddressBookWindow(); - let placeholder = abWindow.cardsPane.cardsList.placeholder; + const abWindow = getAddressBookWindow(); + const placeholder = abWindow.cardsPane.cardsList.placeholder; if (!expectedVisible.length) { Assert.ok( @@ -283,8 +283,8 @@ function checkPlaceholders(expectedVisible = []) { return; } - for (let element of placeholder.children) { - let id = element.id; + for (const element of placeholder.children) { + const id = element.id; if (expectedVisible.includes(id)) { Assert.ok(BrowserTestUtils.is_visible(element), `${id} is visible`); } else { @@ -301,10 +301,10 @@ function checkPlaceholders(expectedVisible = []) { * menu closes. */ async function showBooksContext(index, idToActivate) { - let abWindow = getAddressBookWindow(); - let abDocument = abWindow.document; - let booksList = abWindow.booksList; - let menu = abDocument.getElementById("bookContext"); + const abWindow = getAddressBookWindow(); + const abDocument = abWindow.document; + const booksList = abWindow.booksList; + const menu = abDocument.getElementById("bookContext"); EventUtils.synthesizeMouseAtCenter( booksList @@ -330,10 +330,10 @@ async function showBooksContext(index, idToActivate) { * menu closes. */ async function showCardsContext(index, idToActivate) { - let abWindow = getAddressBookWindow(); - let abDocument = abWindow.document; - let cardsList = abWindow.cardsPane.cardsList; - let menu = abDocument.getElementById("cardContext"); + const abWindow = getAddressBookWindow(); + const abDocument = abWindow.document; + const cardsList = abWindow.cardsPane.cardsList; + const menu = abDocument.getElementById("cardContext"); EventUtils.synthesizeMouseAtCenter( cardsList.getRowAtIndex(index), @@ -358,12 +358,12 @@ async function showCardsContext(index, idToActivate) { * after this search. If no cards are given, checks the placeholder is shown. */ async function doSearch(searchString, ...expectedCards) { - let abWindow = getAddressBookWindow(); - let abDocument = abWindow.document; - let searchBox = abDocument.getElementById("searchInput"); - let cardsList = abWindow.cardsPane.cardsList; + const abWindow = getAddressBookWindow(); + const abDocument = abWindow.document; + const searchBox = abDocument.getElementById("searchInput"); + const cardsList = abWindow.cardsPane.cardsList; - let viewChangePromise = BrowserTestUtils.waitForEvent( + const viewChangePromise = BrowserTestUtils.waitForEvent( cardsList, "viewchange" ); @@ -387,11 +387,11 @@ async function doSearch(searchString, ...expectedCards) { * @param {string} value - The value attribute of the item to activate. */ async function showSortMenu(name, value) { - let abWindow = getAddressBookWindow(); - let abDocument = abWindow.document; + const abWindow = getAddressBookWindow(); + const abDocument = abWindow.document; - let displayButton = abDocument.getElementById("displayButton"); - let sortContext = abDocument.getElementById("sortContext"); + const displayButton = abDocument.getElementById("displayButton"); + const sortContext = abDocument.getElementById("sortContext"); EventUtils.synthesizeMouseAtCenter(displayButton, {}, abWindow); await BrowserTestUtils.waitForPopupEvent(sortContext, "shown"); sortContext.activateItem( @@ -410,12 +410,12 @@ async function showSortMenu(name, value) { * @param {string} value - The value attribute of the item to activate. */ async function showPickerMenu(name, value) { - let abWindow = getAddressBookWindow(); - let cardsHeader = abWindow.cardsPane.table.header; - let pickerButton = cardsHeader.querySelector( + const abWindow = getAddressBookWindow(); + const cardsHeader = abWindow.cardsPane.table.header; + const pickerButton = cardsHeader.querySelector( `th[is="tree-view-table-column-picker"] button` ); - let menupopup = cardsHeader.querySelector( + const menupopup = cardsHeader.querySelector( `th[is="tree-view-table-column-picker"] menupopup` ); EventUtils.synthesizeMouseAtCenter(pickerButton, {}, abWindow); @@ -431,11 +431,11 @@ async function showPickerMenu(name, value) { } async function toggleLayout() { - let abWindow = getAddressBookWindow(); - let abDocument = abWindow.document; + const abWindow = getAddressBookWindow(); + const abDocument = abWindow.document; - let displayButton = abDocument.getElementById("displayButton"); - let sortContext = abDocument.getElementById("sortContext"); + const displayButton = abDocument.getElementById("displayButton"); + const sortContext = abDocument.getElementById("sortContext"); EventUtils.synthesizeMouseAtCenter(displayButton, {}, abWindow); await BrowserTestUtils.waitForPopupEvent(sortContext, "shown"); sortContext.activateItem(abDocument.getElementById("sortContextTableLayout")); @@ -445,10 +445,10 @@ async function toggleLayout() { async function checkComposeWindow(composeWindow, ...expectedAddresses) { await BrowserTestUtils.waitForEvent(composeWindow, "compose-editor-ready"); - let composeDocument = composeWindow.document; - let toAddrRow = composeDocument.getElementById("addressRowTo"); + const composeDocument = composeWindow.document; + const toAddrRow = composeDocument.getElementById("addressRowTo"); - let pills = toAddrRow.querySelectorAll("mail-address-pill"); + const pills = toAddrRow.querySelectorAll("mail-address-pill"); Assert.equal(pills.length, expectedAddresses.length); for (let i = 0; i < expectedAddresses.length; i++) { Assert.equal(pills[i].label, expectedAddresses[i]); @@ -461,13 +461,13 @@ async function checkComposeWindow(composeWindow, ...expectedAddresses) { } function promiseDirectoryRemoved(uri) { - let removePromise = TestUtils.topicObserved("addrbook-directory-deleted"); + const removePromise = TestUtils.topicObserved("addrbook-directory-deleted"); MailServices.ab.deleteAddressBook(uri); return removePromise; } function promiseLoadSubDialog(url) { - let abWindow = getAddressBookWindow(); + const abWindow = getAddressBookWindow(); return new Promise((resolve, reject) => { abWindow.SubDialog._dialogStack.addEventListener( @@ -498,11 +498,11 @@ function promiseLoadSubDialog(url) { ); // Check that stylesheets were injected - let expectedStyleSheetURLs = + const expectedStyleSheetURLs = aEvent.detail.dialog._injectedStyleSheets.slice(0); - for (let styleSheet of aEvent.detail.dialog._frame.contentDocument + for (const styleSheet of aEvent.detail.dialog._frame.contentDocument .styleSheets) { - let i = expectedStyleSheetURLs.indexOf(styleSheet.href); + const i = expectedStyleSheetURLs.indexOf(styleSheet.href); if (i >= 0) { info("found " + styleSheet.href); expectedStyleSheetURLs.splice(i, 1); @@ -523,15 +523,15 @@ function promiseLoadSubDialog(url) { } function formatVCard(strings, ...values) { - let arr = []; - for (let str of strings) { + const arr = []; + for (const str of strings) { arr.push(str); arr.push(values.shift()); } - let lines = arr.join("").split("\n"); - let indent = lines[1].length - lines[1].trimLeft().length; - let outLines = []; - for (let line of lines) { + const lines = arr.join("").split("\n"); + const indent = lines[1].length - lines[1].trimLeft().length; + const outLines = []; + for (const line of lines) { if (line.length > 0) { outLines.push(line.substring(indent) + "\r\n"); } diff --git a/mail/components/cloudfile/test/browser/head.js b/mail/components/cloudfile/test/browser/head.js index 3dd17de883..19e4d7378a 100644 --- a/mail/components/cloudfile/test/browser/head.js +++ b/mail/components/cloudfile/test/browser/head.js @@ -7,11 +7,11 @@ var { MailServices } = ChromeUtils.import( ); add_setup(async function () { - let gAccount = createAccount(); + const gAccount = createAccount(); addIdentity(gAccount); - let rootFolder = gAccount.incomingServer.rootFolder; + const rootFolder = gAccount.incomingServer.rootFolder; - let about3Pane = document.getElementById("tabmail").currentAbout3Pane; + const about3Pane = document.getElementById("tabmail").currentAbout3Pane; about3Pane.displayFolder(rootFolder.URI); await new Promise(resolve => executeSoon(resolve)); }); @@ -22,7 +22,7 @@ function createAccount() { }); MailServices.accounts.createLocalMailAccount(); - let account = MailServices.accounts.accounts[0]; + const account = MailServices.accounts.accounts[0]; info(`Created account ${account.toString()}`); return account; @@ -34,7 +34,7 @@ function cleanUpAccount(account) { } function addIdentity(account) { - let identity = MailServices.accounts.createIdentity(); + const identity = MailServices.accounts.createIdentity(); identity.email = "mochitest@localhost"; account.addIdentity(identity); account.defaultIdentity = identity; diff --git a/mail/components/enterprisepolicies/tests/browser/head.js b/mail/components/enterprisepolicies/tests/browser/head.js index b557ea3d22..d23a9e6e01 100644 --- a/mail/components/enterprisepolicies/tests/browser/head.js +++ b/mail/components/enterprisepolicies/tests/browser/head.js @@ -14,7 +14,7 @@ PoliciesPrefTracker.start(); async function setupPolicyEngineWithJson(json, customSchema) { PoliciesPrefTracker.restoreDefaultValues(); if (typeof json != "object") { - let filePath = getTestFilePath(json ? json : "non-existing-file.json"); + const filePath = getTestFilePath(json ? json : "non-existing-file.json"); return EnterprisePolicyTesting.setupPolicyEngineWithJson( filePath, customSchema @@ -32,12 +32,12 @@ function checkUnlockedPref(prefName, prefValue) { } async function withNewTab(options, taskFn) { - let tab = window.openContentTab(options.url); + const tab = window.openContentTab(options.url); await BrowserTestUtils.browserLoaded(tab.browser); - let result = await taskFn(tab.browser); + const result = await taskFn(tab.browser); - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); tabmail.closeTab(tab); return Promise.resolve(result); } @@ -69,7 +69,7 @@ registerCleanupFunction(async function policies_headjs_finishWithCleanSlate() { function waitForAddonInstall(addon_id) { return new Promise(resolve => { - let listener = { + const listener = { onInstallEnded(install, addon) { if (addon.id == addon_id) { AddonManager.removeInstallListener(listener); @@ -91,7 +91,7 @@ function waitForAddonInstall(addon_id) { function waitForAddonUninstall(addon_id) { return new Promise(resolve => { - let listener = {}; + const listener = {}; listener.onUninstalled = addon => { if (addon.id == addon_id) { AddonManager.removeAddonListener(listener); diff --git a/mail/components/enterprisepolicies/tests/xpcshell/head.js b/mail/components/enterprisepolicies/tests/xpcshell/head.js index 2fcf00a21b..62dc5da95d 100644 --- a/mail/components/enterprisepolicies/tests/xpcshell/head.js +++ b/mail/components/enterprisepolicies/tests/xpcshell/head.js @@ -33,14 +33,14 @@ updateAppInfo({ }); // This initializes the policy engine for xpcshell tests -let policies = Cc["@mozilla.org/enterprisepolicies;1"].getService( +const policies = Cc["@mozilla.org/enterprisepolicies;1"].getService( Ci.nsIObserver ); policies.observe(null, "policies-startup", null); async function setupPolicyEngineWithJson(json, customSchema) { if (typeof json != "object") { - let filePath = do_get_file(json ? json : "non-existing-file.json").path; + const filePath = do_get_file(json ? json : "non-existing-file.json").path; return EnterprisePolicyTesting.setupPolicyEngineWithJson( filePath, customSchema @@ -62,7 +62,7 @@ async function setupPolicyEngineWithJson(json, customSchema) { async function setupPolicyEngineWithJsonWithSearch(json, customSchema) { Services.search.wrappedJSObject.reset(); if (typeof json != "object") { - let filePath = do_get_file(json ? json : "non-existing-file.json").path; + const filePath = do_get_file(json ? json : "non-existing-file.json").path; await EnterprisePolicyTesting.setupPolicyEngineWithJson( filePath, customSchema @@ -70,7 +70,7 @@ async function setupPolicyEngineWithJsonWithSearch(json, customSchema) { } else { await EnterprisePolicyTesting.setupPolicyEngineWithJson(json, customSchema); } - let settingsWritten = lazy.SearchTestUtils.promiseSearchNotification( + const settingsWritten = lazy.SearchTestUtils.promiseSearchNotification( "write-settings-to-disk-complete" ); await Services.search.init(); @@ -120,8 +120,8 @@ function checkClearPref(prefName, prefValue) { } function checkDefaultPref(prefName, prefValue) { - let defaultPrefBranch = Services.prefs.getDefaultBranch(""); - let prefType = defaultPrefBranch.getPrefType(prefName); + const defaultPrefBranch = Services.prefs.getDefaultBranch(""); + const prefType = defaultPrefBranch.getPrefType(prefName); notEqual( prefType, Services.prefs.PREF_INVALID, @@ -130,8 +130,8 @@ function checkDefaultPref(prefName, prefValue) { } function checkUnsetPref(prefName) { - let defaultPrefBranch = Services.prefs.getDefaultBranch(""); - let prefType = defaultPrefBranch.getPrefType(prefName); + const defaultPrefBranch = Services.prefs.getDefaultBranch(""); + const prefType = defaultPrefBranch.getPrefType(prefName); equal( prefType, Services.prefs.PREF_INVALID, diff --git a/mail/components/extensions/test/browser/head.js b/mail/components/extensions/test/browser/head.js index ed25bde87f..db110dde53 100644 --- a/mail/components/extensions/test/browser/head.js +++ b/mail/components/extensions/test/browser/head.js @@ -45,18 +45,18 @@ PromiseTestUtils.allowMatchingRejectionsGlobally( // Adjust timeout to take care of code coverage runs and fission runs to be a // lot slower. -let originalRequestLongerTimeout = requestLongerTimeout; +const originalRequestLongerTimeout = requestLongerTimeout; // eslint-disable-next-line no-global-assign requestLongerTimeout = factor => { - let ccovMultiplier = AppConstants.MOZ_CODE_COVERAGE ? 2 : 1; - let fissionMultiplier = SpecialPowers.useRemoteSubframes ? 2 : 1; + const ccovMultiplier = AppConstants.MOZ_CODE_COVERAGE ? 2 : 1; + const fissionMultiplier = SpecialPowers.useRemoteSubframes ? 2 : 1; originalRequestLongerTimeout(ccovMultiplier * fissionMultiplier * factor); }; requestLongerTimeout(1); add_setup(async () => { await check3PaneState(true, true); - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); if (tabmail.tabInfo.length > 1) { info(`Will close ${tabmail.tabInfo.length - 1} tabs left over from others`); for (let i = tabmail.tabInfo.length - 1; i > 0; i--) { @@ -66,7 +66,7 @@ add_setup(async () => { } }); registerCleanupFunction(() => { - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); is(tabmail.tabInfo.length, 1, "Only one tab open at end of test"); while (tabmail.tabInfo.length > 1) { @@ -78,7 +78,7 @@ registerCleanupFunction(() => { Services.focus.focusedWindow = window; // Focus an element in the main window, then blur it again to avoid it // hijacking keypresses. - let mainWindowElement = document.getElementById("button-appmenu"); + const mainWindowElement = document.getElementById("button-appmenu"); mainWindowElement.focus(); mainWindowElement.blur(); @@ -89,7 +89,7 @@ registerCleanupFunction(() => { // test loaded an extension with a browser_action without setting "useAddonManager" // to either "temporary" or "permanent", which triggers onUninstalled to be // called on extension unload. - let cachedAllowedSpaces = getCachedAllowedSpaces(); + const cachedAllowedSpaces = getCachedAllowedSpaces(); is( cachedAllowedSpaces.size, 0, @@ -119,8 +119,8 @@ async function enforceState(state) { } async function check3PaneState(folderPaneOpen = null, messagePaneOpen = null) { - let tabmail = document.getElementById("tabmail"); - let tab = tabmail.currentTabInfo; + const tabmail = document.getElementById("tabmail"); + const tab = tabmail.currentTabInfo; if (tab.chromeBrowser.contentDocument.readyState != "complete") { await BrowserTestUtils.waitForEvent( tab.chromeBrowser.contentWindow, @@ -128,7 +128,7 @@ async function check3PaneState(folderPaneOpen = null, messagePaneOpen = null) { ); } - let { paneLayout } = tabmail.currentAbout3Pane; + const { paneLayout } = tabmail.currentAbout3Pane; if (folderPaneOpen !== null) { Assert.equal( paneLayout.folderPaneVisible, @@ -173,21 +173,21 @@ function cleanUpAccount(account) { // If the current displayed message/folder belongs to the account to be removed, // select the root folder, otherwise the removal of this account will trigger // a "shouldn't have any listeners left" assertion in nsMsgDatabase.cpp. - let [folder] = window.GetSelectedMsgFolders(); + const [folder] = window.GetSelectedMsgFolders(); if (folder && folder.server && folder.server == account.incomingServer) { - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); tabmail.currentAbout3Pane.displayFolder(folder.server.rootFolder.URI); } - let serverKey = account.incomingServer.key; - let serverType = account.incomingServer.type; + const serverKey = account.incomingServer.key; + const serverType = account.incomingServer.type; info( `Cleaning up ${serverType} account ${account.key} and server ${serverKey}` ); MailServices.accounts.removeAccount(account, true); try { - let server = MailServices.accounts.getIncomingServer(serverKey); + const server = MailServices.accounts.getIncomingServer(serverKey); if (server) { info(`Cleaning up leftover ${serverType} server ${serverKey}`); MailServices.accounts.removeIncomingServer(server, false); @@ -196,7 +196,7 @@ function cleanUpAccount(account) { } function addIdentity(account, email = "mochitest@localhost") { - let identity = MailServices.accounts.createIdentity(); + const identity = MailServices.accounts.createIdentity(); identity.email = email; account.addIdentity(identity); if (!account.defaultIdentity) { @@ -219,8 +219,9 @@ function createMessages(folder, makeMessagesArg) { createMessages.messageGenerator = new MessageGenerator(); } - let messages = createMessages.messageGenerator.makeMessages(makeMessagesArg); - let messageStrings = messages.map(message => message.toMboxString()); + const messages = + createMessages.messageGenerator.makeMessages(makeMessagesArg); + const messageStrings = messages.map(message => message.toMboxString()); folder.QueryInterface(Ci.nsIMsgLocalMailFolder); folder.addMessageBatch(messageStrings); } @@ -230,7 +231,7 @@ async function createMessageFromFile(folder, path) { // A cheap hack to make this acceptable to addMessageBatch. It works for // existing uses but may not work for future uses. - let fromAddress = message.match(/From: .* <(.*@.*)>/)[0]; + const fromAddress = message.match(/From: .* <(.*@.*)>/)[0]; message = `From ${fromAddress}\r\n${message}`; folder.QueryInterface(Ci.nsIMsgLocalMailFolder); @@ -249,7 +250,7 @@ async function focusWindow(win) { return; } - let promise = new Promise(resolve => { + const promise = new Promise(resolve => { win.addEventListener( "focus", function () { @@ -268,7 +269,7 @@ function promisePopupShown(popup) { if (popup.state == "open") { resolve(); } else { - let onPopupShown = event => { + const onPopupShown = event => { popup.removeEventListener("popupshown", onPopupShown); resolve(); }; @@ -318,7 +319,7 @@ var awaitExtensionPanel = async function ( win = window, awaitLoad = true ) { - let { originalTarget: browser } = await BrowserTestUtils.waitForEvent( + const { originalTarget: browser } = await BrowserTestUtils.waitForEvent( win.document, "WebExtPopupLoaded", true, @@ -338,8 +339,8 @@ function getBrowserActionPopup(extension, win = window) { } function closeBrowserAction(extension, win = window) { - let popup = getBrowserActionPopup(extension, win); - let hidden = BrowserTestUtils.waitForEvent(popup, "popuphidden"); + const popup = getBrowserActionPopup(extension, win); + const hidden = BrowserTestUtils.waitForEvent(popup, "popuphidden"); popup.hidePopup(); return hidden; @@ -353,7 +354,7 @@ async function openNewMailWindow(options = {}) { ); } - let win = window.openDialog( + const win = window.openDialog( "chrome://messenger/content/messenger.xhtml", "_blank", "chrome,all,dialog=no" @@ -367,17 +368,17 @@ async function openNewMailWindow(options = {}) { } async function openComposeWindow(account) { - let params = Cc[ + const params = Cc[ "@mozilla.org/messengercompose/composeparams;1" ].createInstance(Ci.nsIMsgComposeParams); - let composeFields = Cc[ + const composeFields = Cc[ "@mozilla.org/messengercompose/composefields;1" ].createInstance(Ci.nsIMsgCompFields); params.identity = account.defaultIdentity; params.composeFields = composeFields; - let composeWindowPromise = BrowserTestUtils.domWindowOpened( + const composeWindowPromise = BrowserTestUtils.domWindowOpened( undefined, async win => { await BrowserTestUtils.waitForEvent(win, "load"); @@ -402,7 +403,7 @@ async function openMessageInTab(msgHdr) { // Ensure the behaviour pref is set to open a new tab. It is the default, // but you never know. - let oldPrefValue = Services.prefs.getIntPref("mail.openMessageBehavior"); + const oldPrefValue = Services.prefs.getIntPref("mail.openMessageBehavior"); Services.prefs.setIntPref( "mail.openMessageBehavior", MailConsts.OpenMessageBehavior.NEW_TAB @@ -410,8 +411,8 @@ async function openMessageInTab(msgHdr) { MailUtils.displayMessages([msgHdr]); Services.prefs.setIntPref("mail.openMessageBehavior", oldPrefValue); - let win = Services.wm.getMostRecentWindow("mail:3pane"); - let tab = win.document.getElementById("tabmail").currentTabInfo; + const win = Services.wm.getMostRecentWindow("mail:3pane"); + const tab = win.document.getElementById("tabmail").currentTabInfo; await BrowserTestUtils.waitForEvent(tab.chromeBrowser, "MsgLoaded"); return tab; } @@ -421,7 +422,7 @@ async function openMessageInWindow(msgHdr) { throw new Error("No message passed to openMessageInWindow"); } - let messageWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded( + const messageWindowPromise = BrowserTestUtils.domWindowOpenedAndLoaded( undefined, async win => win.document.documentURI == @@ -429,7 +430,7 @@ async function openMessageInWindow(msgHdr) { ); MailUtils.openMessageInNewWindow(msgHdr); - let messageWindow = await messageWindowPromise; + const messageWindow = await messageWindowPromise; await BrowserTestUtils.waitForEvent(messageWindow, "MsgLoaded"); return messageWindow; } @@ -458,10 +459,10 @@ async function promiseMessageLoaded(browser, msgHdr) { * @param {string} [fields.subject] */ async function checkComposeHeaders(expected) { - let composeWindows = [...Services.wm.getEnumerator("msgcompose")]; + const composeWindows = [...Services.wm.getEnumerator("msgcompose")]; is(composeWindows.length, 1); - let composeDocument = composeWindows[0].document; - let composeFields = composeWindows[0].gMsgCompose.compFields; + const composeDocument = composeWindows[0].document; + const composeFields = composeWindows[0].gMsgCompose.compFields; await new Promise(resolve => composeWindows[0].setTimeout(resolve)); @@ -477,8 +478,8 @@ async function checkComposeHeaders(expected) { ); } - let checkField = (fieldName, elementId) => { - let pills = composeDocument + const checkField = (fieldName, elementId) => { + const pills = composeDocument .getElementById(elementId) .getElementsByTagName("mail-address-pill"); @@ -503,7 +504,7 @@ async function checkComposeHeaders(expected) { checkField("followupTo", "addressRowFollowup"); checkField("newsgroups", "addressRowNewsgroups"); - let subject = composeDocument.getElementById("msgSubject").value; + const subject = composeDocument.getElementById("msgSubject").value; if ("subject" in expected) { is(subject, expected.subject, "subject is correct"); } else { @@ -512,10 +513,10 @@ async function checkComposeHeaders(expected) { if (expected.overrideDefaultFcc) { if (expected.overrideDefaultFccFolder) { - let server = MailServices.accounts.getAccount( + const server = MailServices.accounts.getAccount( expected.overrideDefaultFccFolder.accountId ).incomingServer; - let rootURI = server.rootFolder.URI; + const rootURI = server.rootFolder.URI; is( rootURI + expected.overrideDefaultFccFolder.path, composeFields.fcc, @@ -532,10 +533,10 @@ async function checkComposeHeaders(expected) { } if (expected.additionalFccFolder) { - let server = MailServices.accounts.getAccount( + const server = MailServices.accounts.getAccount( expected.additionalFccFolder.accountId ).incomingServer; - let rootURI = server.rootFolder.URI; + const rootURI = server.rootFolder.URI; is( rootURI + expected.additionalFccFolder.path, composeFields.fcc2, @@ -562,7 +563,7 @@ async function checkComposeHeaders(expected) { expected.returnReceipt, "returnReceipt in composeFields should be correct" ); - for (let item of composeDocument.querySelectorAll(`menuitem[command="cmd_toggleReturnReceipt"], + for (const item of composeDocument.querySelectorAll(`menuitem[command="cmd_toggleReturnReceipt"], toolbarbutton[command="cmd_toggleReturnReceipt"]`)) { is( item.getAttribute("checked") == "true", @@ -599,14 +600,14 @@ async function checkComposeHeaders(expected) { [Ci.nsIMsgCompSendFormat.Both, "format_both"], [Ci.nsIMsgCompSendFormat.Auto, "format_auto"], ]); - let expectedFormat = deliveryFormats[expected.deliveryFormat || "auto"]; + const expectedFormat = deliveryFormats[expected.deliveryFormat || "auto"]; is( expectedFormat, composeFields.deliveryFormat, "deliveryFormat in composeFields should be correct" ); - for (let [format, id] of formatToId.entries()) { - let menuitem = composeDocument.getElementById(id); + for (const [format, id] of formatToId.entries()) { + const menuitem = composeDocument.getElementById(id); is( format == expectedFormat, menuitem.getAttribute("checked") == "true", @@ -618,17 +619,18 @@ async function checkComposeHeaders(expected) { async function synthesizeMouseAtCenterAndRetry(selector, event, browser) { let success = false; - let type = event.type || "click"; + const type = event.type || "click"; for (let retries = 0; !success && retries < 2; retries++) { - let clickPromise = BrowserTestUtils.waitForContentEvent(browser, type).then( - () => true - ); + const clickPromise = BrowserTestUtils.waitForContentEvent( + browser, + type + ).then(() => true); // Linux: Sometimes the actor used to simulate the mouse event in the content process does not // react, even though the content page signals to be fully loaded. There is no status signal // we could wait for, the loaded page *should* be ready at this point. To mitigate, we wait // for the click event and if we do not see it within a certain time, we click again. // eslint-disable-next-line mozilla/no-arbitrary-setTimeout - let failPromise = new Promise(r => + const failPromise = new Promise(r => browser.ownerGlobal.setTimeout(r, 500) ).then(() => false); @@ -639,12 +641,12 @@ async function synthesizeMouseAtCenterAndRetry(selector, event, browser) { } async function openContextMenu(selector = "#img1", win = window) { - let contentAreaContextMenu = win.document.getElementById("browserContext"); - let popupShownPromise = BrowserTestUtils.waitForEvent( + const contentAreaContextMenu = win.document.getElementById("browserContext"); + const popupShownPromise = BrowserTestUtils.waitForEvent( contentAreaContextMenu, "popupshown" ); - let tabmail = document.getElementById("tabmail"); + const tabmail = document.getElementById("tabmail"); await synthesizeMouseAtCenterAndRetry( selector, { type: "mousedown", button: 2 }, @@ -660,11 +662,11 @@ async function openContextMenu(selector = "#img1", win = window) { } async function openContextMenuInPopup(extension, selector, win = window) { - let contentAreaContextMenu = + const contentAreaContextMenu = win.top.document.getElementById("browserContext"); - let stack = getBrowserActionPopup(extension, win); - let browser = stack.querySelector("browser"); - let popupShownPromise = BrowserTestUtils.waitForEvent( + const stack = getBrowserActionPopup(extension, win); + const browser = stack.querySelector("browser"); + const popupShownPromise = BrowserTestUtils.waitForEvent( contentAreaContextMenu, "popupshown" ); @@ -687,9 +689,9 @@ async function closeExtensionContextMenu( modifiers = {}, win = window ) { - let contentAreaContextMenu = + const contentAreaContextMenu = win.top.document.getElementById("browserContext"); - let popupHiddenPromise = BrowserTestUtils.waitForEvent( + const popupHiddenPromise = BrowserTestUtils.waitForEvent( contentAreaContextMenu, "popuphidden" ); @@ -713,9 +715,9 @@ async function openSubmenu(submenuItem, win = window) { } async function closeContextMenu(contextMenu) { - let contentAreaContextMenu = + const contentAreaContextMenu = contextMenu || document.getElementById("browserContext"); - let popupHiddenPromise = BrowserTestUtils.waitForEvent( + const popupHiddenPromise = BrowserTestUtils.waitForEvent( contentAreaContextMenu, "popuphidden" ); @@ -724,7 +726,7 @@ async function closeContextMenu(contextMenu) { } async function getUtilsJS() { - let response = await fetch(getRootDirectory(gTestPath) + "utils.js"); + const response = await fetch(getRootDirectory(gTestPath) + "utils.js"); return response.text(); } @@ -732,7 +734,7 @@ async function checkContent(browser, expected) { await SpecialPowers.spawn(browser, [expected], expected => { let body = content.document.body; Assert.ok(body, "body"); - let computedStyle = content.getComputedStyle(body); + const computedStyle = content.getComputedStyle(body); if ("backgroundColor" in expected) { Assert.equal( @@ -760,19 +762,19 @@ async function checkContent(browser, expected) { function contentTabOpenPromise(tabmail, url) { return new Promise(resolve => { - let tabMonitor = { + const tabMonitor = { onTabTitleChanged(aTab) {}, onTabClosing(aTab) {}, onTabPersist(aTab) {}, onTabRestored(aTab) {}, onTabSwitched(aNewTab, aOldTab) {}, async onTabOpened(aTab) { - let result = awaitBrowserLoaded( + const result = awaitBrowserLoaded( aTab.linkedBrowser, urlToMatch => urlToMatch == url ).then(() => aTab); - let reporterListener = { + const reporterListener = { QueryInterface: ChromeUtils.generateQI([ "nsIWebProgressListener", "nsISupportsWeakReference", @@ -843,7 +845,7 @@ async function run_popup_test(configData) { let backend_script = configData.backend_script; - let extensionDetails = { + const extensionDetails = { files: { "popup.html": ` @@ -899,14 +901,14 @@ async function run_popup_test(configData) { switch (configData.testType) { case "open-with-mouse-click": backend_script = async function (extension, configData) { - let win = configData.window; + const win = configData.window; await extension.startup(); await promiseAnimationFrame(win); await new Promise(resolve => win.setTimeout(resolve)); await extension.awaitMessage("ready"); - let buttonId = `${configData.actionType}_mochi_test-${configData.moduleName}-toolbarbutton`; + const buttonId = `${configData.actionType}_mochi_test-${configData.moduleName}-toolbarbutton`; let toolbarId; switch (configData.actionType) { case "compose_action": @@ -963,7 +965,7 @@ async function run_popup_test(configData) { "Button should be available in unified toolbar mail space" ); - let icon = button.querySelector(".button-icon"); + const icon = button.querySelector(".button-icon"); is( getComputedStyle(icon).content, `url("chrome://messenger/content/extension.svg")`, @@ -990,7 +992,7 @@ async function run_popup_test(configData) { `Button should have been added to currentset xulStore of toolbar ${toolbarId}` ); - let icon = button.querySelector(".toolbarbutton-icon"); + const icon = button.querySelector(".toolbarbutton-icon"); is( getComputedStyle(icon).listStyleImage, `url("chrome://messenger/content/extension.svg")`, @@ -1058,7 +1060,7 @@ async function run_popup_test(configData) { ); } } else { - let hasFiredBefore = await clickedPromise; + const hasFiredBefore = await clickedPromise; await promiseAnimationFrame(win); await new Promise(resolve => win.setTimeout(resolve)); if (toolbarId === "unified-toolbar") { @@ -1140,7 +1142,7 @@ async function run_popup_test(configData) { // With popup. extensionDetails.files["background.js"] = async function () { browser.test.log("popup background script ran"); - let popupPromise = window.getPopupOpenedPromise(); + const popupPromise = window.getPopupOpenedPromise(); browser.test.sendMessage("ready"); await popupPromise; await browser[window.apiName].setTitle({ title: "New title" }); @@ -1169,7 +1171,7 @@ async function run_popup_test(configData) { browser.test.assertEq(0, info.button); browser.test.assertTrue(Array.isArray(info.modifiers)); browser.test.assertEq(0, info.modifiers.length); - let [currentTab] = await browser.tabs.query({ + const [currentTab] = await browser.tabs.query({ active: true, currentWindow: true, }); @@ -1191,8 +1193,8 @@ async function run_popup_test(configData) { case "open-with-menu-command": extensionDetails.manifest.permissions = ["menus"]; backend_script = async function (extension, configData) { - let win = configData.window; - let buttonId = `${configData.actionType}_mochi_test-${configData.moduleName}-toolbarbutton`; + const win = configData.window; + const buttonId = `${configData.actionType}_mochi_test-${configData.moduleName}-toolbarbutton`; let menuId = "toolbar-context-menu"; let isUnifiedToolbar = false; if ( @@ -1222,10 +1224,13 @@ async function run_popup_test(configData) { }; extension.onMessage("triggerClick", async () => { - let button = getButton(win); - let menu = win.document.getElementById(menuId); - let onShownPromise = extension.awaitMessage("onShown"); - let shownPromise = BrowserTestUtils.waitForEvent(menu, "popupshown"); + const button = getButton(win); + const menu = win.document.getElementById(menuId); + const onShownPromise = extension.awaitMessage("onShown"); + const shownPromise = BrowserTestUtils.waitForEvent( + menu, + "popupshown" + ); EventUtils.synthesizeMouseAtCenter( button, { type: "contextmenu" }, @@ -1235,7 +1240,7 @@ async function run_popup_test(configData) { await onShownPromise; await new Promise(resolve => win.setTimeout(resolve)); - let menuitem = win.document.getElementById( + const menuitem = win.document.getElementById( `${configData.actionType}_mochi_test-menuitem-_testmenu` ); Assert.ok(menuitem); @@ -1253,7 +1258,7 @@ async function run_popup_test(configData) { await extension.awaitFinish(); // Check the open state of the action button. - let button = getButton(win); + const button = getButton(win); await TestUtils.waitForCondition( () => button.getAttribute("open") != "true", "Button should not have open state after the popup closed." @@ -1281,7 +1286,7 @@ async function run_popup_test(configData) { browser.test.sendMessage("onShown", args); }); - let popupPromise = window.getPopupOpenedPromise(); + const popupPromise = window.getPopupOpenedPromise(); await window.sendMessage("triggerClick"); await popupPromise; @@ -1337,8 +1342,8 @@ async function run_popup_test(configData) { browser.test.sendMessage("onShown", args); }); - let clickPromise = new Promise(resolve => { - let listener = async (tab, info) => { + const clickPromise = new Promise(resolve => { + const listener = async (tab, info) => { browser[window.apiName].onClicked.removeListener(listener); browser.test.assertEq("object", typeof tab); browser.test.assertEq("object", typeof info); @@ -1381,13 +1386,13 @@ async function run_popup_test(configData) { configData.default_windows; } - let extension = ExtensionTestUtils.loadExtension(extensionDetails); + const extension = ExtensionTestUtils.loadExtension(extensionDetails); await backend_script(extension, configData); } async function run_action_button_order_test(configs, window, actionType) { // Get camelCase API names from action type. - let apiName = actionType.replace(/_([a-z])/g, function (g) { + const apiName = actionType.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); }); @@ -1396,13 +1401,13 @@ async function run_action_button_order_test(configs, window, actionType) { } function test_buttons(configs, window, toolbars) { - for (let toolbarId of toolbars) { - let expected = configs.filter(e => e.toolbar == toolbarId); - let selector = + for (const toolbarId of toolbars) { + const expected = configs.filter(e => e.toolbar == toolbarId); + const selector = toolbarId === "unified-toolbar" ? `#unifiedToolbarContent [extension$="@mochi.test"]` : `#${toolbarId} toolbarbutton[id$="${get_id("")}"]`; - let buttons = window.document.querySelectorAll(selector); + const buttons = window.document.querySelectorAll(selector); Assert.equal( expected.length, buttons.length, @@ -1427,8 +1432,8 @@ async function run_action_button_order_test(configs, window, actionType) { } // Create extension data. - let toolbars = new Set(); - for (let config of configs) { + const toolbars = new Set(); + for (const config of configs) { toolbars.add(config.toolbar); config.extensionData = { useAddonManager: "permanent", @@ -1453,35 +1458,35 @@ async function run_action_button_order_test(configs, window, actionType) { } // Test order of buttons after first install. - for (let config of configs) { + for (const config of configs) { config.extension = ExtensionTestUtils.loadExtension(config.extensionData); await config.extension.startup(); } test_buttons(configs, window, toolbars); // Disable all buttons. - for (let config of configs) { - let addon = await AddonManager.getAddonByID(config.extension.id); + for (const config of configs) { + const addon = await AddonManager.getAddonByID(config.extension.id); await addon.disable(); } test_buttons([], window, toolbars); // Re-enable all buttons in reversed order, displayed order should not change. - for (let config of [...configs].reverse()) { - let addon = await AddonManager.getAddonByID(config.extension.id); + for (const config of [...configs].reverse()) { + const addon = await AddonManager.getAddonByID(config.extension.id); await addon.enable(); } test_buttons(configs, window, toolbars); // Re-install all extensions in reversed order, displayed order should not change. - for (let config of [...configs].reverse()) { + for (const config of [...configs].reverse()) { config.extension2 = ExtensionTestUtils.loadExtension(config.extensionData); await config.extension2.startup(); } test_buttons(configs, window, toolbars); // Remove all extensions. - for (let config of [...configs].reverse()) { + for (const config of [...configs].reverse()) { await config.extension.unload(); await config.extension2.unload(); } diff --git a/mail/components/extensions/test/browser/head_menus.js b/mail/components/extensions/test/browser/head_menus.js index 346c4ca044..efb800fc88 100644 --- a/mail/components/extensions/test/browser/head_menus.js +++ b/mail/components/extensions/test/browser/head_menus.js @@ -28,7 +28,7 @@ var URL_BASE = * @returns {Promise} A promise that resolves when the menu appears. */ function leftClick(menu, element) { - let shownPromise = BrowserTestUtils.waitForEvent(menu, "popupshown"); + const shownPromise = BrowserTestUtils.waitForEvent(menu, "popupshown"); EventUtils.synthesizeMouseAtCenter(element, {}, element.ownerGlobal); return shownPromise; } @@ -41,7 +41,7 @@ function leftClick(menu, element) { * @returns {Promise} A promise that resolves when the menu appears. */ function rightClick(menu, element) { - let shownPromise = BrowserTestUtils.waitForEvent(menu, "popupshown"); + const shownPromise = BrowserTestUtils.waitForEvent(menu, "popupshown"); EventUtils.synthesizeMouseAtCenter( element, { type: "contextmenu" }, @@ -60,7 +60,7 @@ function rightClick(menu, element) { * @returns {Promise} A promise that resolves when the menu appears. */ async function rightClickOnContent(menu, selector, browser) { - let shownPromise = BrowserTestUtils.waitForEvent(menu, "popupshown"); + const shownPromise = BrowserTestUtils.waitForEvent(menu, "popupshown"); await synthesizeMouseAtCenterAndRetry( selector, { type: "contextmenu" }, @@ -90,7 +90,7 @@ async function rightClickOnContent(menu, selector, browser) { * @param {boolean} expectedTab.mailTab */ async function checkShownEvent(extension, expectedInfo, expectedTab) { - let [info, tab] = await extension.awaitMessage("onShown"); + const [info, tab] = await extension.awaitMessage("onShown"); Assert.deepEqual(info.menuIds, expectedInfo.menuIds); Assert.deepEqual(info.contexts, expectedInfo.contexts); @@ -107,7 +107,7 @@ async function checkShownEvent(extension, expectedInfo, expectedTab) { } } - for (let infoKey of ["displayedFolder", "selectedFolder"]) { + for (const infoKey of ["displayedFolder", "selectedFolder"]) { Assert.equal( !!info[infoKey], !!expectedInfo[infoKey], @@ -180,7 +180,7 @@ async function checkShownEvent(extension, expectedInfo, expectedTab) { * @param {boolean} expectedTab.mailTab */ async function checkClickedEvent(extension, expectedInfo, expectedTab) { - let [info, tab] = await extension.awaitMessage("onClicked"); + const [info, tab] = await extension.awaitMessage("onClicked"); Assert.equal(info.selectionText, expectedInfo.selectionText, "selectionText"); Assert.equal(info.linkText, expectedInfo.linkText, "linkText"); @@ -188,7 +188,7 @@ async function checkClickedEvent(extension, expectedInfo, expectedTab) { Assert.equal(info.menuItemId, expectedInfo.menuItemId, "menuItemId"); } - for (let infoKey of ["pageUrl", "linkUrl", "srcUrl"]) { + for (const infoKey of ["pageUrl", "linkUrl", "srcUrl"]) { Assert.equal( !!info[infoKey], !!expectedInfo[infoKey], @@ -209,10 +209,10 @@ async function checkClickedEvent(extension, expectedInfo, expectedTab) { } async function getMenuExtension(manifest) { - let details = { + const details = { files: { "background.js": async () => { - let contexts = [ + const contexts = [ "audio", "compose_action", "compose_action_menu", @@ -239,7 +239,7 @@ async function getMenuExtension(manifest) { contexts.push("browser_action", "browser_action_menu"); } - for (let context of contexts) { + for (const context of contexts) { browser.menus.create({ id: context, title: context, @@ -274,7 +274,7 @@ async function getMenuExtension(manifest) { } details.manifest.permissions.push("menus"); console.log(JSON.stringify(details, 2)); - let extension = ExtensionTestUtils.loadExtension(details); + const extension = ExtensionTestUtils.loadExtension(details); if (details.manifest.host_permissions) { // MV3 has to manually grant the requested permission. await ExtensionPermissions.add("menus@mochi.test", { @@ -294,7 +294,7 @@ async function subtest_content( ) { await awaitBrowserLoaded(browser, url => url != "about:blank"); - let menuId = browser.getAttribute("context"); + const menuId = browser.getAttribute("context"); let ownerDocument; if (browser.ownerGlobal.parent.location.href == "about:3pane") { ownerDocument = browser.ownerGlobal.parent.document; @@ -303,7 +303,7 @@ async function subtest_content( } else { ownerDocument = browser.ownerDocument; } - let menu = ownerDocument.getElementById(menuId); + const menu = ownerDocument.getElementById(menuId); await synthesizeMouseAtCenterAndRetry("body", {}, browser); @@ -333,7 +333,7 @@ async function subtest_content( info("Test selection."); await SpecialPowers.spawn(browser, [], () => { - let text = content.document.querySelector("p"); + const text = content.document.querySelector("p"); content.getSelection().selectAllChildren(text); }); await rightClickOnContent(menu, "p", browser); @@ -442,7 +442,9 @@ async function openExtensionSubMenu(menu) { // The extension submenu ends with a number, which increases over time, but it // does not have a underscore. let submenu; - for (let item of menu.querySelectorAll("[id^=menus_mochi_test-menuitem-]")) { + for (const item of menu.querySelectorAll( + "[id^=menus_mochi_test-menuitem-]" + )) { if (!item.id.includes("-_")) { submenu = item; break; @@ -451,7 +453,7 @@ async function openExtensionSubMenu(menu) { Assert.ok(submenu, `Found submenu: ${submenu.id}`); // Open submenu. - let submenuPromise = BrowserTestUtils.waitForEvent(menu, "popupshown"); + const submenuPromise = BrowserTestUtils.waitForEvent(menu, "popupshown"); submenu.openMenu(true); await submenuPromise; @@ -467,8 +469,8 @@ async function subtest_compose_body( ) { await awaitBrowserLoaded(browser, url => url != "about:blank"); - let ownerDocument = browser.ownerDocument; - let menu = ownerDocument.getElementById(browser.getAttribute("context")); + const ownerDocument = browser.ownerDocument; + const menu = ownerDocument.getElementById(browser.getAttribute("context")); await synthesizeMouseAtCenterAndRetry("body", {}, browser); @@ -477,7 +479,7 @@ async function subtest_compose_body( await rightClickOnContent(menu, "body", browser); Assert.ok(menu.querySelector(`#menus_mochi_test-menuitem-_compose_body`)); Assert.ok(menu.querySelector(`#menus_mochi_test-menuitem-_editable`)); - let hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden"); + const hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden"); menu.hidePopup(); await hiddenPromise; // Sometimes, the popup will open then instantly disappear. It seems to @@ -500,12 +502,12 @@ async function subtest_compose_body( info("Test selection."); { await SpecialPowers.spawn(browser, [], () => { - let text = content.document.querySelector("p"); + const text = content.document.querySelector("p"); content.getSelection().selectAllChildren(text); }); await rightClickOnContent(menu, "p", browser); - let submenu = await openExtensionSubMenu(menu); + const submenu = await openExtensionSubMenu(menu); await checkShownEvent( extension, @@ -523,8 +525,8 @@ async function subtest_compose_body( ); Assert.ok(submenu.querySelector("#menus_mochi_test-menuitem-_editable")); - let hiddenPromise = BrowserTestUtils.waitForEvent(submenu, "popuphidden"); - let clickedPromise = checkClickedEvent( + const hiddenPromise = BrowserTestUtils.waitForEvent(submenu, "popuphidden"); + const clickedPromise = checkClickedEvent( extension, { pageUrl, @@ -549,7 +551,7 @@ async function subtest_compose_body( info("Test link."); { await rightClickOnContent(menu, "a", browser); - let submenu = await openExtensionSubMenu(menu); + const submenu = await openExtensionSubMenu(menu); await checkShownEvent( extension, @@ -566,8 +568,8 @@ async function subtest_compose_body( submenu.querySelector("#menus_mochi_test-menuitem-_compose_body") ); - let hiddenPromise = BrowserTestUtils.waitForEvent(submenu, "popuphidden"); - let clickedPromise = checkClickedEvent( + const hiddenPromise = BrowserTestUtils.waitForEvent(submenu, "popuphidden"); + const clickedPromise = checkClickedEvent( extension, { pageUrl, @@ -593,7 +595,7 @@ async function subtest_compose_body( info("Test image."); { await rightClickOnContent(menu, "img", browser); - let submenu = await openExtensionSubMenu(menu); + const submenu = await openExtensionSubMenu(menu); await checkShownEvent( extension, @@ -610,8 +612,8 @@ async function subtest_compose_body( submenu.querySelector("#menus_mochi_test-menuitem-_compose_body") ); - let hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden"); - let clickedPromise = checkClickedEvent( + const hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden"); + const clickedPromise = checkClickedEvent( extension, { pageUrl, @@ -644,7 +646,7 @@ async function subtest_element( pageUrl, tab ) { - for (let selectedTest of [false, true]) { + for (const selectedTest of [false, true]) { element.focus(); if (selectedTest) { element.value = "This is selected text."; @@ -653,10 +655,10 @@ async function subtest_element( element.value = ""; } - let event = await rightClick(element.ownerGlobal, element); - let menu = event.target; - let trigger = menu.triggerNode; - let menuitem = menu.querySelector("#menus_mochi_test-menuitem-_editable"); + const event = await rightClick(element.ownerGlobal, element); + const menu = event.target; + const trigger = menu.triggerNode; + const menuitem = menu.querySelector("#menus_mochi_test-menuitem-_editable"); Assert.equal( element.id, trigger.id, @@ -688,7 +690,7 @@ async function subtest_element( // extension submenu. Open the submenu. let submenu = null; if (selectedTest) { - for (let foundMenu of menu.querySelectorAll( + for (const foundMenu of menu.querySelectorAll( "[id^='menus_mochi_test-menuitem-']" )) { if (!foundMenu.id.startsWith("menus_mochi_test-menuitem-_")) { @@ -696,7 +698,7 @@ async function subtest_element( } } Assert.ok(submenu, "Submenu found."); - let submenuPromise = BrowserTestUtils.waitForEvent( + const submenuPromise = BrowserTestUtils.waitForEvent( element.ownerGlobal, "popupshown" ); @@ -704,11 +706,11 @@ async function subtest_element( await submenuPromise; } - let hiddenPromise = BrowserTestUtils.waitForEvent( + const hiddenPromise = BrowserTestUtils.waitForEvent( element.ownerGlobal, "popuphidden" ); - let clickedPromise = checkClickedEvent( + const clickedPromise = checkClickedEvent( extension, { pageUrl, diff --git a/mail/components/extensions/test/xpcshell/head-imap.js b/mail/components/extensions/test/xpcshell/head-imap.js index ac85c52b64..764ba5de2e 100644 --- a/mail/components/extensions/test/xpcshell/head-imap.js +++ b/mail/components/extensions/test/xpcshell/head-imap.js @@ -6,7 +6,7 @@ var IS_IMAP = true; -let wrappedCreateAccount = createAccount; +const wrappedCreateAccount = createAccount; createAccount = function (type = "imap") { return wrappedCreateAccount(type); }; diff --git a/mail/components/extensions/test/xpcshell/head-nntp.js b/mail/components/extensions/test/xpcshell/head-nntp.js index 0b4a56d0dc..0312b74b83 100644 --- a/mail/components/extensions/test/xpcshell/head-nntp.js +++ b/mail/components/extensions/test/xpcshell/head-nntp.js @@ -6,7 +6,7 @@ var IS_NNTP = true; -let wrappedCreateAccount = createAccount; +const wrappedCreateAccount = createAccount; createAccount = function (type = "nntp") { return wrappedCreateAccount(type); }; diff --git a/mail/components/extensions/test/xpcshell/head.js b/mail/components/extensions/test/xpcshell/head.js index f8c0c0e7b9..15656d30b1 100644 --- a/mail/components/extensions/test/xpcshell/head.js +++ b/mail/components/extensions/test/xpcshell/head.js @@ -30,15 +30,15 @@ var IS_IMAP = false; var IS_NNTP = false; function formatVCard(strings, ...values) { - let arr = []; - for (let str of strings) { + const arr = []; + for (const str of strings) { arr.push(str); arr.push(values.shift()); } - let lines = arr.join("").split("\n"); - let indent = lines[1].length - lines[1].trimLeft().length; - let outLines = []; - for (let line of lines) { + const lines = arr.join("").split("\n"); + const indent = lines[1].length - lines[1].trimLeft().length; + const outLines = []; + for (const line of lines) { if (line.length > 0) { outLines.push(line.substring(indent) + "\r\n"); } @@ -79,15 +79,15 @@ function createAccount(type = "none") { } function cleanUpAccount(account) { - let serverKey = account.incomingServer.key; - let serverType = account.incomingServer.type; + const serverKey = account.incomingServer.key; + const serverType = account.incomingServer.type; info( `Cleaning up ${serverType} account ${account.key} and server ${serverKey}` ); MailServices.accounts.removeAccount(account, true); try { - let server = MailServices.accounts.getIncomingServer(serverKey); + const server = MailServices.accounts.getIncomingServer(serverKey); if (server) { info(`Cleaning up leftover ${serverType} server ${serverKey}`); MailServices.accounts.removeIncomingServer(server, false); @@ -100,7 +100,7 @@ registerCleanupFunction(() => { }); function addIdentity(account, email = "xpcshell@localhost") { - let identity = MailServices.accounts.createIdentity(); + const identity = MailServices.accounts.createIdentity(); identity.email = email; account.addIdentity(identity); if (!account.defaultIdentity) { @@ -113,12 +113,12 @@ function addIdentity(account, email = "xpcshell@localhost") { async function createSubfolder(parent, name) { if (parent.server.type == "nntp") { createNewsgroup(name); - let account = MailServices.accounts.FindAccountForServer(parent.server); + const account = MailServices.accounts.FindAccountForServer(parent.server); subscribeNewsgroup(account, name); return parent.getChildNamed(name); } - let promiseAdded = PromiseTestUtils.promiseFolderAdded(name); + const promiseAdded = PromiseTestUtils.promiseFolderAdded(name); parent.createSubfolder(name, null); await promiseAdded; return parent.getChildNamed(name); @@ -132,7 +132,8 @@ function createMessages(folder, makeMessagesArg) { createMessages.messageGenerator = new MessageGenerator(); } - let messages = createMessages.messageGenerator.makeMessages(makeMessagesArg); + const messages = + createMessages.messageGenerator.makeMessages(makeMessagesArg); return addGeneratedMessages(folder, messages); } @@ -145,7 +146,7 @@ class FakeGeneratedMessage { } toMboxString() { // A cheap hack. It works for existing uses but may not work for future uses. - let fromAddress = this.msg.match(/From: .* <(.*@.*)>/)[0]; + const fromAddress = this.msg.match(/From: .* <(.*@.*)>/)[0]; let mBoxString = `From ${fromAddress}\r\n${this.msg}`; // Ensure a trailing empty line. if (!mBoxString.endsWith("\r\n")) { @@ -156,7 +157,7 @@ class FakeGeneratedMessage { } async function createMessageFromFile(folder, path) { - let message = await IOUtils.readUTF8(path); + const message = await IOUtils.readUTF8(path); return addGeneratedMessages(folder, [new FakeGeneratedMessage(message)]); } @@ -172,7 +173,7 @@ async function addGeneratedMessages(folder, messages) { return NNTPServer.addMessages(folder, messages); } - let messageStrings = messages.map(message => message.toMboxString()); + const messageStrings = messages.map(message => message.toMboxString()); folder.QueryInterface(Ci.nsIMsgLocalMailFolder); folder.addMessageBatch(messageStrings); folder.callFilterPlugins(null); @@ -185,9 +186,8 @@ async function getUtilsJS() { var IMAPServer = { open() { - let { ImapDaemon, ImapMessage, IMAP_RFC3501_handler } = ChromeUtils.import( - "resource://testing-common/mailnews/Imapd.jsm" - ); + const { ImapDaemon, ImapMessage, IMAP_RFC3501_handler } = + ChromeUtils.import("resource://testing-common/mailnews/Imapd.jsm"); IMAPServer.ImapMessage = ImapMessage; this.daemon = new ImapDaemon(); @@ -207,15 +207,15 @@ var IMAPServer = { }, addMessages(folder, messages) { - let fakeFolder = IMAPServer.daemon.getMailbox(folder.name); + const fakeFolder = IMAPServer.daemon.getMailbox(folder.name); messages.forEach(message => { if (typeof message != "string") { message = message.toMessageString(); } - let msgURI = Services.io.newURI( + const msgURI = Services.io.newURI( "data:text/plain;base64," + btoa(message) ); - let imapMsg = new IMAPServer.ImapMessage( + const imapMsg = new IMAPServer.ImapMessage( msgURI.spec, fakeFolder.uidnext++, [] @@ -243,7 +243,7 @@ function createNewsgroup(group) { var NNTPServer = { open() { - let { NNTP_RFC977_handler, NntpDaemon } = ChromeUtils.import( + const { NNTP_RFC977_handler, NntpDaemon } = ChromeUtils.import( "resource://testing-common/mailnews/Nntpd.jsm" ); @@ -273,11 +273,11 @@ var NNTPServer = { }, addMessages(folder, messages) { - let { NewsArticle } = ChromeUtils.import( + const { NewsArticle } = ChromeUtils.import( "resource://testing-common/mailnews/Nntpd.jsm" ); - let group = folder.name; + const group = folder.name; messages.forEach(message => { if (typeof message != "string") { message = message.toMessageString(); @@ -286,7 +286,7 @@ var NNTPServer = { if (!message.endsWith("\r\n")) { message = message + "\r\n"; } - let article = new NewsArticle(message); + const article = new NewsArticle(message); article.groups = [group]; this.daemon.addArticle(article); }); diff --git a/mail/components/im/test/browser/head.js b/mail/components/im/test/browser/head.js index b80d274149..8428d1ed2c 100644 --- a/mail/components/im/test/browser/head.js +++ b/mail/components/im/test/browser/head.js @@ -9,8 +9,8 @@ var { IMServices } = ChromeUtils.importESModule( ); async function openChatTab() { - let tabmail = document.getElementById("tabmail"); - let chatMode = tabmail.tabModes.chat; + const tabmail = document.getElementById("tabmail"); + const chatMode = tabmail.tabModes.chat; if (chatMode.tabs.length == 1) { tabmail.selectedTab = chatMode.tabs[0]; @@ -25,8 +25,8 @@ async function openChatTab() { } async function closeChatTab() { - let tabmail = document.getElementById("tabmail"); - let chatMode = tabmail.tabModes.chat; + const tabmail = document.getElementById("tabmail"); + const chatMode = tabmail.tabModes.chat; if (chatMode.tabs.length == 1) { tabmail.closeTab(chatMode.tabs[0]); @@ -85,7 +85,7 @@ function waitForConversationLoad(browser) { function waitForNotification(target, expectedTopic) { let observer; - let promise = new Promise(resolve => { + const promise = new Promise(resolve => { observer = { observe(subject, topic, data) { if (topic === expectedTopic) { diff --git a/mail/components/preferences/test/browser/head.js b/mail/components/preferences/test/browser/head.js index 12cbdb17f1..b65ce5aad7 100644 --- a/mail/components/preferences/test/browser/head.js +++ b/mail/components/preferences/test/browser/head.js @@ -5,8 +5,8 @@ /* import-globals-from ../../../../base/content/utilityOverlay.js */ async function openNewPrefsTab(paneID, scrollPaneTo, otherArgs) { - let tabmail = document.getElementById("tabmail"); - let prefsTabMode = tabmail.tabModes.preferencesTab; + const tabmail = document.getElementById("tabmail"); + const prefsTabMode = tabmail.tabModes.preferencesTab; is(prefsTabMode.tabs.length, 0, "Prefs tab is not open"); @@ -22,7 +22,7 @@ async function openNewPrefsTab(paneID, scrollPaneTo, otherArgs) { ok(prefsDocument.URL.startsWith("about:preferences"), "Prefs tab is open"); prefsDocument = prefsTabMode.tabs[0].browser.contentDocument; - let prefsWindow = prefsDocument.ownerGlobal; + const prefsWindow = prefsDocument.ownerGlobal; prefsWindow.resizeTo(screen.availWidth, screen.availHeight); if (paneID) { @@ -41,7 +41,7 @@ async function openNewPrefsTab(paneID, scrollPaneTo, otherArgs) { registerCleanupOnce(); await new Promise(resolve => prefsWindow.setTimeout(resolve)); - let container = prefsDocument.getElementById("preferencesContainer"); + const container = prefsDocument.getElementById("preferencesContainer"); if (scrollPaneTo && container.scrollHeight > container.clientHeight) { Assert.greater( container.scrollTop, @@ -53,13 +53,13 @@ async function openNewPrefsTab(paneID, scrollPaneTo, otherArgs) { } async function openExistingPrefsTab(paneID, scrollPaneTo, otherArgs) { - let tabmail = document.getElementById("tabmail"); - let prefsTabMode = tabmail.tabModes.preferencesTab; + const tabmail = document.getElementById("tabmail"); + const prefsTabMode = tabmail.tabModes.preferencesTab; is(prefsTabMode.tabs.length, 1, "Prefs tab is open"); - let prefsDocument = prefsTabMode.tabs[0].browser.contentDocument; - let prefsWindow = prefsDocument.ownerGlobal; + const prefsDocument = prefsTabMode.tabs[0].browser.contentDocument; + const prefsWindow = prefsDocument.ownerGlobal; prefsWindow.resizeTo(screen.availWidth, screen.availHeight); if (paneID && prefsWindow.gLastCategory.category != paneID) { @@ -91,8 +91,8 @@ function registerCleanupOnce() { async function closePrefsTab() { info("Closing prefs tab"); - let tabmail = document.getElementById("tabmail"); - let prefsTab = tabmail.tabModes.preferencesTab.tabs[0]; + const tabmail = document.getElementById("tabmail"); + const prefsTab = tabmail.tabModes.preferencesTab.tabs[0]; if (prefsTab) { tabmail.closeTab(prefsTab); } @@ -114,10 +114,10 @@ async function closePrefsTab() { * the toggling of the checkbox. */ async function testCheckboxes(paneID, scrollPaneTo, ...tests) { - for (let initiallyChecked of [true, false]) { + for (const initiallyChecked of [true, false]) { info(`Opening ${paneID} with prefs set to ${initiallyChecked}`); - for (let test of tests) { + for (const test of tests) { let wantedValue = initiallyChecked; if (test.prefValues) { wantedValue = wantedValue ? test.prefValues[1] : test.prefValues[0]; @@ -129,17 +129,17 @@ async function testCheckboxes(paneID, scrollPaneTo, ...tests) { } } - let { prefsDocument, prefsWindow } = await openNewPrefsTab( + const { prefsDocument, prefsWindow } = await openNewPrefsTab( paneID, scrollPaneTo ); - let testUIState = function (test, checked) { + const testUIState = function (test, checked) { let wantedValue = checked; if (test.prefValues) { wantedValue = wantedValue ? test.prefValues[1] : test.prefValues[0]; } - let checkbox = prefsDocument.getElementById(test.checkboxID); + const checkbox = prefsDocument.getElementById(test.checkboxID); is( checkbox.checked, checked, @@ -165,13 +165,13 @@ async function testCheckboxes(paneID, scrollPaneTo, ...tests) { if (test.enabledInverted) { disabled = !disabled; } - for (let selector of test.enabledElements) { - let elements = prefsDocument.querySelectorAll(selector); + for (const selector of test.enabledElements) { + const elements = prefsDocument.querySelectorAll(selector); ok( elements.length >= 1, `At least one element matched '${selector}'` ); - for (let element of elements) { + for (const element of elements) { is( element.disabled, !disabled, @@ -182,22 +182,23 @@ async function testCheckboxes(paneID, scrollPaneTo, ...tests) { } }; - let testUnaffected = function (ids, states) { + const testUnaffected = function (ids, states) { ids.forEach((sel, index) => { - let isOk = prefsDocument.querySelector(sel).disabled === states[index]; + const isOk = + prefsDocument.querySelector(sel).disabled === states[index]; is(isOk, true, `Element "${sel}" is unaffected`); }); }; - for (let test of tests) { + for (const test of tests) { info(`Checking ${test.checkboxID}`); - let unaffectedSelectors = test.unaffectedElements || []; - let unaffectedStates = unaffectedSelectors.map( + const unaffectedSelectors = test.unaffectedElements || []; + const unaffectedStates = unaffectedSelectors.map( sel => prefsDocument.querySelector(sel).disabled ); - let checkbox = prefsDocument.getElementById(test.checkboxID); + const checkbox = prefsDocument.getElementById(test.checkboxID); checkbox.scrollIntoView(false); testUIState(test, initiallyChecked); @@ -228,8 +229,8 @@ async function testCheckboxes(paneID, scrollPaneTo, ...tests) { * radio button is selected (optional) */ async function testRadioButtons(paneID, scrollPaneTo, ...tests) { - for (let { pref, states } of tests) { - for (let initialState of states) { + for (const { pref, states } of tests) { + for (const initialState of states) { info(`Opening ${paneID} with ${pref} set to ${initialState.prefValue}`); if (typeof initialState.prefValue == "number") { @@ -240,26 +241,26 @@ async function testRadioButtons(paneID, scrollPaneTo, ...tests) { Services.prefs.setCharPref(pref, initialState.prefValue); } - let { prefsDocument, prefsWindow } = await openNewPrefsTab( + const { prefsDocument, prefsWindow } = await openNewPrefsTab( paneID, scrollPaneTo ); - let testUIState = function (currentState) { + const testUIState = function (currentState) { info(`Testing with ${pref} set to ${currentState.prefValue}`); - for (let state of states) { - let isCurrentState = state == currentState; - let radio = prefsDocument.getElementById(state.id); + for (const state of states) { + const isCurrentState = state == currentState; + const radio = prefsDocument.getElementById(state.id); is(radio.selected, isCurrentState, `${state.id}.selected`); if (state.enabledElements) { - for (let selector of state.enabledElements) { - let elements = prefsDocument.querySelectorAll(selector); + for (const selector of state.enabledElements) { + const elements = prefsDocument.querySelectorAll(selector); ok( elements.length >= 1, `At least one element matched '${selector}'` ); - for (let element of elements) { + for (const element of elements) { is( element.disabled, !isCurrentState, @@ -293,17 +294,17 @@ async function testRadioButtons(paneID, scrollPaneTo, ...tests) { // Check the initial setup is correct. testUIState(initialState); // Cycle through possible values, checking each one. - for (let state of states) { + for (const state of states) { if (state == initialState) { continue; } - let radio = prefsDocument.getElementById(state.id); + const radio = prefsDocument.getElementById(state.id); radio.scrollIntoView(false); EventUtils.synthesizeMouseAtCenter(radio, {}, prefsWindow); testUIState(state); } // Go back to the initial value. - let initialRadio = prefsDocument.getElementById(initialState.id); + const initialRadio = prefsDocument.getElementById(initialState.id); initialRadio.scrollIntoView(false); EventUtils.synthesizeMouseAtCenter(initialRadio, {}, prefsWindow); testUIState(initialState); diff --git a/mail/test/static/head.js b/mail/test/static/head.js index a1cce8735a..4d671d2a64 100644 --- a/mail/test/static/head.js +++ b/mail/test/static/head.js @@ -27,12 +27,12 @@ function generateURIsFromDirTree(dir, extensions) { if (!Array.isArray(extensions)) { extensions = [extensions]; } - let dirQueue = [dir.path]; + const dirQueue = [dir.path]; return (async function () { - let rv = []; + const rv = []; while (dirQueue.length) { - let nextDir = dirQueue.shift(); - let { subdirs, files } = await iterateOverPath(nextDir, extensions); + const nextDir = dirQueue.shift(); + const { subdirs, files } = await iterateOverPath(nextDir, extensions); dirQueue.push(...subdirs); rv.push(...files); } @@ -51,22 +51,22 @@ function generateURIsFromDirTree(dir, extensions) { * @param extensions the file extensions we're interested in. */ async function iterateOverPath(path, extensions) { - let parentDir = new LocalFile(path); - let subdirs = []; - let files = []; + const parentDir = new LocalFile(path); + const subdirs = []; + const files = []; // Iterate through the directory - for (let childPath of await IOUtils.getChildren(path)) { - let stat = await IOUtils.stat(childPath); + for (const childPath of await IOUtils.getChildren(path)) { + const stat = await IOUtils.stat(childPath); if (stat.type === "directory") { subdirs.push(childPath); } else if (extensions.some(extension => childPath.endsWith(extension))) { - let file = parentDir.clone(); + const file = parentDir.clone(); file.append(PathUtils.filename(childPath)); // the build system might leave dead symlinks hanging around, which are // returned as part of the directory iterator, but don't actually exist: if (file.exists()) { - let uriSpec = getURLForFile(file); + const uriSpec = getURLForFile(file); files.push(Services.io.newURI(uriSpec)); } } else if ( @@ -75,10 +75,10 @@ async function iterateOverPath(path, extensions) { childPath.endsWith(".zip") || childPath.endsWith(".xpi") ) { - let file = parentDir.clone(); + const file = parentDir.clone(); file.append(PathUtils.filename(childPath)); - for (let extension of extensions) { - let jarEntryIterator = generateEntriesFromJarFile(file, extension); + for (const extension of extensions) { + const jarEntryIterator = generateEntriesFromJarFile(file, extension); files.push(...jarEntryIterator); } } @@ -102,15 +102,15 @@ function getURLForFile(file) { * @param extension the extension we're interested in. */ function* generateEntriesFromJarFile(jarFile, extension) { - let zr = new ZipReader(jarFile); + const zr = new ZipReader(jarFile); const kURIStart = getURLForFile(jarFile); - for (let entry of zr.findEntries("*" + extension + "$")) { + for (const entry of zr.findEntries("*" + extension + "$")) { // Ignore the JS cache which is stored in omni.ja if (entry.startsWith("jsloader") || entry.startsWith("jssubloader")) { continue; } - let entryURISpec = "jar:" + kURIStart + "!/" + entry; + const entryURISpec = "jar:" + kURIStart + "!/" + entry; yield Services.io.newURI(entryURISpec); } zr.close(); @@ -118,7 +118,7 @@ function* generateEntriesFromJarFile(jarFile, extension) { function fetchFile(uri) { return new Promise((resolve, reject) => { - let xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); xhr.responseType = "text"; xhr.open("GET", uri, true); xhr.onreadystatechange = function () { @@ -141,13 +141,13 @@ function fetchFile(uri) { } async function throttledMapPromises(iterable, task, limit = 64) { - let promises = new Set(); - for (let data of iterable) { + const promises = new Set(); + for (const data of iterable) { while (promises.size >= limit) { await Promise.race(promises); } - let promise = task(data); + const promise = task(data); if (promise) { promise.finally(() => promises.delete(promise)); promises.add(promise); diff --git a/mailnews/addrbook/test/unit/head.js b/mailnews/addrbook/test/unit/head.js index 7a5155ea26..7b07771881 100644 --- a/mailnews/addrbook/test/unit/head.js +++ b/mailnews/addrbook/test/unit/head.js @@ -24,7 +24,7 @@ registerCleanupFunction(function () { }); function promiseDirectoryRemoved(uri) { - let removePromise = TestUtils.topicObserved("addrbook-directory-deleted"); + const removePromise = TestUtils.topicObserved("addrbook-directory-deleted"); MailServices.ab.deleteAddressBook(uri); return removePromise; } @@ -49,15 +49,15 @@ acObserver.prototype = { }; function formatVCard(strings, ...values) { - let arr = []; - for (let str of strings) { + const arr = []; + for (const str of strings) { arr.push(str); arr.push(values.shift()); } - let lines = arr.join("").split("\n"); - let indent = lines[1].length - lines[1].trimLeft().length; - let outLines = []; - for (let line of lines) { + const lines = arr.join("").split("\n"); + const indent = lines[1].length - lines[1].trimLeft().length; + const outLines = []; + for (const line of lines) { if (line.length > 0) { outLines.push(line.substring(indent) + "\r\n"); } diff --git a/mailnews/addrbook/test/unit/head_cardDAV.js b/mailnews/addrbook/test/unit/head_cardDAV.js index 8eea75d463..c27ffd5a98 100644 --- a/mailnews/addrbook/test/unit/head_cardDAV.js +++ b/mailnews/addrbook/test/unit/head_cardDAV.js @@ -48,14 +48,14 @@ async function initDirectory() { if (!Services.logins.findLogins(CardDAVServer.origin, null, "test").length) { // Save a username and password to the login manager. - let loginInfo = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance( - Ci.nsILoginInfo - ); + const loginInfo = Cc[ + "@mozilla.org/login-manager/loginInfo;1" + ].createInstance(Ci.nsILoginInfo); loginInfo.init(CardDAVServer.origin, null, "test", "bob", "bob", "", ""); await Services.logins.addLoginAsync(loginInfo); } - let directory = new CardDAVDirectory(); + const directory = new CardDAVDirectory(); directory.init("jscarddav://carddav.sqlite"); return directory; } @@ -63,7 +63,7 @@ async function initDirectory() { async function clearDirectory(directory) { await directory.cleanUp(); - let database = do_get_profile(); + const database = do_get_profile(); database.append("carddav.sqlite"); database.remove(false); } @@ -74,11 +74,11 @@ async function checkCardsOnServer(expectedCards) { await fetch(`${CardDAVServer.origin}/ping`); info("Checking cards on server are correct."); - let actualCards = [...CardDAVServer.cards]; + const actualCards = [...CardDAVServer.cards]; Assert.equal(actualCards.length, Object.keys(expectedCards).length); for (let [href, { etag, vCard }] of actualCards) { - let baseName = href + const baseName = href .substring(CardDAVServer.path.length) .replace(/\.vcf$/, ""); info(baseName); @@ -92,7 +92,7 @@ async function checkCardsOnServer(expectedCards) { } } -let observer = { +const observer = { notifications: { "addrbook-contact-created": [], "addrbook-contact-updated": [], @@ -105,21 +105,21 @@ let observer = { } this.isInited = true; - for (let key of Object.keys(this.notifications)) { + for (const key of Object.keys(this.notifications)) { Services.obs.addObserver(observer, key); } }, checkAndClearNotifications(expected) { Assert.deepEqual(this.notifications, expected); - for (let array of Object.values(this.notifications)) { + for (const array of Object.values(this.notifications)) { array.length = 0; } }, observe(subject, topic) { - let uid = subject.QueryInterface(Ci.nsIAbCard).UID; + const uid = subject.QueryInterface(Ci.nsIAbCard).UID; info(`${topic}: ${uid}`); if (this.pendingPromise && this.pendingPromise.topic == topic) { - let promise = this.pendingPromise; + const promise = this.pendingPromise; this.pendingPromise = null; promise.resolve(uid); return; @@ -143,7 +143,7 @@ add_task(async () => { // Checks two vCard strings have the same lines, in any order. // Not very smart but smart enough. function vCardEqual(lhs, rhs, message) { - let lhsLines = lhs.split("\r\n").sort(); - let rhsLines = rhs.split("\r\n").sort(); + const lhsLines = lhs.split("\r\n").sort(); + const rhsLines = rhs.split("\r\n").sort(); Assert.deepEqual(lhsLines, rhsLines, message); } diff --git a/mailnews/compose/test/unit/head_compose.js b/mailnews/compose/test/unit/head_compose.js index 6f874335e5..8791d2452c 100644 --- a/mailnews/compose/test/unit/head_compose.js +++ b/mailnews/compose/test/unit/head_compose.js @@ -59,7 +59,7 @@ function setupServerDaemon(handler) { } function getBasicSmtpServer(port = 1, hostname = "localhost") { - let server = localAccountUtils.create_outgoing_server( + const server = localAccountUtils.create_outgoing_server( port, "user", "password", @@ -75,7 +75,7 @@ function getBasicSmtpServer(port = 1, hostname = "localhost") { function getSmtpIdentity(senderName, smtpServer) { // Set up the identity - let identity = MailServices.accounts.createIdentity(); + const identity = MailServices.accounts.createIdentity(); identity.email = senderName; identity.smtpServerKey = smtpServer.key; @@ -157,14 +157,14 @@ var progressListener = { }; function createMessage(aAttachment) { - let fields = Cc[ + const fields = Cc[ "@mozilla.org/messengercompose/composefields;1" ].createInstance(Ci.nsIMsgCompFields); fields.from = "Nobody "; let attachments = []; if (aAttachment) { - let attachment = Cc[ + const attachment = Cc[ "@mozilla.org/messengercompose/attachment;1" ].createInstance(Ci.nsIMsgAttachment); if (aAttachment instanceof Ci.nsIFile) { @@ -186,17 +186,17 @@ function richCreateMessage( identity = null, account = null ) { - let params = Cc[ + const params = Cc[ "@mozilla.org/messengercompose/composeparams;1" ].createInstance(Ci.nsIMsgComposeParams); params.composeFields = fields; - let msgCompose = MailServices.compose.initCompose(params); + const msgCompose = MailServices.compose.initCompose(params); if (identity === null) { identity = getSmtpIdentity(null, getBasicSmtpServer()); } - let rootFolder = localAccountUtils.rootFolder; + const rootFolder = localAccountUtils.rootFolder; gDraftFolder = null; // Make sure the drafts folder is empty try { @@ -206,21 +206,21 @@ function richCreateMessage( gDraftFolder = rootFolder.createLocalSubfolder("Drafts"); } // Clear all messages - let msgs = [...gDraftFolder.msgDatabase.enumerateMessages()]; + const msgs = [...gDraftFolder.msgDatabase.enumerateMessages()]; if (msgs.length > 0) { gDraftFolder.deleteMessages(msgs, null, true, false, null, false); } // Set attachment fields.removeAttachments(); - for (let attachment of attachments) { + for (const attachment of attachments) { fields.addAttachment(attachment); } - let progress = Cc["@mozilla.org/messenger/progress;1"].createInstance( + const progress = Cc["@mozilla.org/messenger/progress;1"].createInstance( Ci.nsIMsgProgress ); - let promise = new Promise((resolve, reject) => { + const promise = new Promise((resolve, reject) => { progressListener.resolve = resolve; progressListener.reject = reject; }); @@ -237,7 +237,7 @@ function richCreateMessage( function getAttachmentFromContent(aContent) { function getBoundaryStringFromContent() { - let found = aContent.match( + const found = aContent.match( /Content-Type: multipart\/mixed;\s+boundary="(.*?)"/ ); Assert.notEqual(found, null); @@ -246,8 +246,8 @@ function getAttachmentFromContent(aContent) { return found[1]; } - let boundary = getBoundaryStringFromContent(aContent); - let regex = new RegExp( + const boundary = getBoundaryStringFromContent(aContent); + const regex = new RegExp( "\\r\\n\\r\\n--" + boundary + "\\r\\n" + @@ -257,7 +257,7 @@ function getAttachmentFromContent(aContent) { "--", "m" ); - let attachments = aContent.match(regex); + const attachments = aContent.match(regex); Assert.notEqual(attachments, null); Assert.equal(attachments.length, 2); return attachments[1]; @@ -270,7 +270,7 @@ function getAttachmentFromContent(aContent) { * @returns {string} */ function getMessageBody(content) { - let separatorIndex = content.indexOf("\r\n\r\n"); + const separatorIndex = content.indexOf("\r\n\r\n"); Assert.equal(content.slice(-2), "\r\n", "Should end with a line break."); return content.slice(separatorIndex + 4, -2); } diff --git a/mailnews/extensions/newsblog/test/unit/head_feeds.js b/mailnews/extensions/newsblog/test/unit/head_feeds.js index 004e1acf68..eb29ff130c 100644 --- a/mailnews/extensions/newsblog/test/unit/head_feeds.js +++ b/mailnews/extensions/newsblog/test/unit/head_feeds.js @@ -11,15 +11,15 @@ var { localAccountUtils } = ChromeUtils.import( "resource://testing-common/mailnews/LocalAccountUtils.jsm" ); -let { FeedParser } = ChromeUtils.import("resource:///modules/FeedParser.jsm"); -let { Feed } = ChromeUtils.import("resource:///modules/Feed.jsm"); -let { FeedUtils } = ChromeUtils.import("resource:///modules/FeedUtils.jsm"); -let { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); +const { FeedParser } = ChromeUtils.import("resource:///modules/FeedParser.jsm"); +const { Feed } = ChromeUtils.import("resource:///modules/Feed.jsm"); +const { FeedUtils } = ChromeUtils.import("resource:///modules/FeedUtils.jsm"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); // Set up local web server to serve up test files. // We run it on a random port so that other tests can run concurrently // even if they also run a web server. -let httpServer = new HttpServer(); +const httpServer = new HttpServer(); httpServer.registerDirectory("/", do_get_file("resources")); httpServer.start(-1); const SERVER_PORT = httpServer.identity.primaryPort; diff --git a/mailnews/imap/test/unit/head_server.js b/mailnews/imap/test/unit/head_server.js index b092b9a21b..18c788754c 100644 --- a/mailnews/imap/test/unit/head_server.js +++ b/mailnews/imap/test/unit/head_server.js @@ -117,7 +117,7 @@ function makeServer(daemon, infoString, otherProps) { } function createLocalIMAPServer(port, hostname = "localhost") { - let server = localAccountUtils.create_incoming_server( + const server = localAccountUtils.create_incoming_server( "imap", port, "user", @@ -145,7 +145,7 @@ function do_check_transaction(fromServer, expected, withParams) { fromServer = fromServer[fromServer.length - 1]; } - let realTransaction = []; + const realTransaction = []; for (let i = 0; i < fromServer.them.length; i++) { var line = fromServer.them[i]; // e.g. '1 login "user" "password"' var components = line.split(" "); @@ -172,12 +172,12 @@ function do_check_transaction(fromServer, expected, withParams) { */ function addImapMessage() { let messages = []; - let messageGenerator = new MessageGenerator(); // eslint-disable-line no-undef + const messageGenerator = new MessageGenerator(); // eslint-disable-line no-undef messages = messages.concat(messageGenerator.makeMessage()); - let dataUri = Services.io.newURI( + const dataUri = Services.io.newURI( "data:text/plain;base64," + btoa(messages[0].toMessageString()) ); - let imapMsg = new ImapMessage(dataUri.spec, IMAPPump.mailbox.uidnext++, []); + const imapMsg = new ImapMessage(dataUri.spec, IMAPPump.mailbox.uidnext++, []); IMAPPump.mailbox.addMessage(imapMsg); } diff --git a/mailnews/intl/test/unit/head_CharsetConversionTests.js b/mailnews/intl/test/unit/head_CharsetConversionTests.js index f1ae6c7155..83bb51cc54 100644 --- a/mailnews/intl/test/unit/head_CharsetConversionTests.js +++ b/mailnews/intl/test/unit/head_CharsetConversionTests.js @@ -10,7 +10,7 @@ function CreateScriptableConverter() { } function checkDecode(converter, charset, inText, expectedText) { - let manager = Cc["@mozilla.org/charset-converter-manager;1"].getService( + const manager = Cc["@mozilla.org/charset-converter-manager;1"].getService( Ci.nsICharsetConverterManager ); @@ -30,7 +30,7 @@ function checkDecode(converter, charset, inText, expectedText) { } function checkEncode(converter, charset, inText, expectedText) { - let manager = Cc["@mozilla.org/charset-converter-manager;1"].getService( + const manager = Cc["@mozilla.org/charset-converter-manager;1"].getService( Ci.nsICharsetConverterManager ); diff --git a/mailnews/jsaccount/test/unit/head_jsaccount.js b/mailnews/jsaccount/test/unit/head_jsaccount.js index a3c37dea1f..f3e496898a 100644 --- a/mailnews/jsaccount/test/unit/head_jsaccount.js +++ b/mailnews/jsaccount/test/unit/head_jsaccount.js @@ -19,7 +19,7 @@ var { localAccountUtils } = ChromeUtils.import( ); // Load the test components. -let contracts = [ +const contracts = [ { contractID: "@mozilla.org/jsaccount/testjafoourl;1", classID: "{73F98539-A59F-4F6F-9A72-D83A08646C23}", @@ -37,9 +37,9 @@ let contracts = [ }, ]; -let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); -for (let { contractID, classID, source } of contracts) { - let scope = {}; +const registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); +for (const { contractID, classID, source } of contracts) { + const scope = {}; Services.scriptloader.loadSubScript( Services.io.newFileURI(do_get_file(source)).spec, scope diff --git a/mailnews/local/test/unit/head_maillocal.js b/mailnews/local/test/unit/head_maillocal.js index dff897b36e..2faf72f35f 100644 --- a/mailnews/local/test/unit/head_maillocal.js +++ b/mailnews/local/test/unit/head_maillocal.js @@ -67,7 +67,7 @@ function setupServerDaemon(debugOption) { function createPop3ServerAndLocalFolders(port, hostname = "localhost") { localAccountUtils.loadLocalMailAccount(); - let server = localAccountUtils.create_incoming_server( + const server = localAccountUtils.create_incoming_server( "pop3", port, "fred", @@ -162,7 +162,7 @@ function do_check_transaction(real, expected) { } function create_temporary_directory() { - let directory = Services.dirsvc.get("TmpD", Ci.nsIFile); + const directory = Services.dirsvc.get("TmpD", Ci.nsIFile); directory.append("mailFolder"); directory.createUnique(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0700", 8)); return directory; @@ -172,8 +172,8 @@ function create_sub_folders(parent, subFolders) { parent.leafName = parent.leafName + ".sbd"; parent.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0700", 8)); - for (let folder in subFolders) { - let subFolder = parent.clone(); + for (const folder in subFolders) { + const subFolder = parent.clone(); subFolder.append(subFolders[folder].name); subFolder.create(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0600", 8)); if (subFolders[folder].subFolders) { @@ -183,13 +183,13 @@ function create_sub_folders(parent, subFolders) { } function create_mail_directory(subFolders) { - let root = create_temporary_directory(); + const root = create_temporary_directory(); - for (let folder in subFolders) { + for (const folder in subFolders) { if (!subFolders[folder].subFolders) { continue; } - let directory = root.clone(); + const directory = root.clone(); directory.append(subFolders[folder].name); create_sub_folders(directory, subFolders[folder].subFolders); } @@ -198,8 +198,8 @@ function create_mail_directory(subFolders) { } function setup_mailbox(type, mailboxPath) { - let user = Services.uuid.generateUUID().toString(); - let incomingServer = MailServices.accounts.createIncomingServer( + const user = Services.uuid.generateUUID().toString(); + const incomingServer = MailServices.accounts.createIncomingServer( user, "Local Folder", type diff --git a/mailnews/mapi/test/unit/head_mapi.js b/mailnews/mapi/test/unit/head_mapi.js index d80b7da173..415d4d9359 100644 --- a/mailnews/mapi/test/unit/head_mapi.js +++ b/mailnews/mapi/test/unit/head_mapi.js @@ -33,29 +33,29 @@ function setupServerDaemon(handler) { return new SMTP_RFC2821_handler(d); }; } - let daemon = new SmtpDaemon(); - let server = new nsMailServer(handler, daemon); + const daemon = new SmtpDaemon(); + const server = new nsMailServer(handler, daemon); return [daemon, server]; } function getBasicSmtpServer() { // We need to have a default account for MAPI. localAccountUtils.loadLocalMailAccount(); - let incoming = localAccountUtils.create_incoming_server( + const incoming = localAccountUtils.create_incoming_server( "pop3", POP3_PORT, "user", "password" ); - let server = localAccountUtils.create_outgoing_server( + const server = localAccountUtils.create_outgoing_server( SMTP_PORT, "user", "password" ); // We also need to have a working identity, including an email address. - let account = MailServices.accounts.FindAccountForServer(incoming); + const account = MailServices.accounts.FindAccountForServer(incoming); localAccountUtils.associate_servers(account, server, true); - let identity = account.defaultIdentity; + const identity = account.defaultIdentity; identity.email = "tinderbox@tinderbox.invalid"; MailServices.accounts.defaultAccount = account; @@ -80,15 +80,15 @@ function loadMAPILibrary() { Services.prefs.setBoolPref("mapi.blind-send.warn", false); // The macros that are used in the definitions - let WINAPI = ctypes.winapi_abi; - let ULONG = ctypes.unsigned_long; - let LHANDLE = ULONG.ptr; - let LPSTR = ctypes.char.ptr; - let LPVOID = ctypes.voidptr_t; - let FLAGS = ctypes.unsigned_long; + const WINAPI = ctypes.winapi_abi; + const ULONG = ctypes.unsigned_long; + const LHANDLE = ULONG.ptr; + const LPSTR = ctypes.char.ptr; + const LPVOID = ctypes.voidptr_t; + const FLAGS = ctypes.unsigned_long; // Define all of the MAPI structs we need to use. - let functionData = {}; + const functionData = {}; functionData.MapiRecipDesc = new ctypes.StructType("gMapi.MapiRecipDesc", [ { ulReserved: ULONG }, { ulRecipClass: ULONG }, @@ -97,7 +97,7 @@ function loadMAPILibrary() { { ulEIDSize: ULONG }, { lpEntryID: LPVOID }, ]); - let lpMapiRecipDesc = functionData.MapiRecipDesc.ptr; + const lpMapiRecipDesc = functionData.MapiRecipDesc.ptr; functionData.MapiFileDesc = new ctypes.StructType("gMapi.MapiFileDesc", [ { ulReserved: ULONG }, @@ -107,7 +107,7 @@ function loadMAPILibrary() { { lpszFileName: LPSTR }, { lpFileType: LPVOID }, ]); - let lpMapiFileDesc = functionData.MapiFileDesc.ptr; + const lpMapiFileDesc = functionData.MapiFileDesc.ptr; functionData.MapiMessage = new ctypes.StructType("gMapi.MapiMessage", [ { ulReserved: ULONG }, @@ -123,11 +123,11 @@ function loadMAPILibrary() { { nFileCount: ULONG }, { lpFiles: lpMapiFileDesc }, ]); - let lpMapiMessage = functionData.MapiMessage.ptr; + const lpMapiMessage = functionData.MapiMessage.ptr; // Load the MAPI library. We're using our definition instead of the global // MAPI definition. - let mapi = ctypes.open("mozMapi32.dll"); + const mapi = ctypes.open("mozMapi32.dll"); // Load the MAPI functions, // see https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_types diff --git a/mailnews/mime/jsmime/test/unit/head_xpcshell_glue.js b/mailnews/mime/jsmime/test/unit/head_xpcshell_glue.js index 6f7fca89f1..d6349aede9 100644 --- a/mailnews/mime/jsmime/test/unit/head_xpcshell_glue.js +++ b/mailnews/mime/jsmime/test/unit/head_xpcshell_glue.js @@ -53,7 +53,7 @@ function require(path) { let file; if (path.startsWith("test/")) { - let name = path.substring("test/".length); + const name = path.substring("test/".length); file = "resource://testing-common/jsmime/" + name + ".js"; } else { file = "resource:///modules/jsmime/" + path + ".js"; @@ -99,17 +99,17 @@ function MochaSuite(name) { // The real code for running a suite of tests, written as async function. MochaSuite.prototype._runSuite = async function () { info("Running suite " + this.name); - for (let setup_ of this.setup) { + for (const setup_ of this.setup) { await runFunction(setup_); } - for (let test_ of this.tests) { + for (const test_ of this.tests) { info("Running test " + test_.name); await runFunction(test_.test); } - for (let suite_ of this.suites) { + for (const suite_ of this.suites) { await suite_.runSuite(); } - for (let fn of this.teardown) { + for (const fn of this.teardown) { await runFunction(fn); } info("Finished suite " + this.name); @@ -122,7 +122,7 @@ MochaSuite.prototype.runSuite = function () { // Run the given function, returning a promise of when the test will complete. function runFunction(fn) { - let completed = new Promise(function (resolve, reject) { + const completed = new Promise(function (resolve, reject) { function onEnd(error) { if (error !== undefined) { reject(error); @@ -149,7 +149,7 @@ function suite(name, tests) { if (/[\x80-]/.exec(name)) { name = ""; } - let suiteParent = currentSuite; + const suiteParent = currentSuite; currentSuite = new MochaSuite(name); suiteParent.suites.push(currentSuite); tests(); diff --git a/mailnews/mime/test/unit/head_mime.js b/mailnews/mime/test/unit/head_mime.js index 868a7ceace..d3125a140f 100644 --- a/mailnews/mime/test/unit/head_mime.js +++ b/mailnews/mime/test/unit/head_mime.js @@ -32,15 +32,15 @@ registerCleanupFunction(function () { }); function apply_mime_conversion(msgUri, smimeHeaderSink) { - let service = MailServices.messageServiceFromURI(msgUri); + const service = MailServices.messageServiceFromURI(msgUri); // This is what we listen on in the end. - let listener = new PromiseTestUtils.PromiseStreamListener(); + const listener = new PromiseTestUtils.PromiseStreamListener(); // Make the underlying channel--we need this for the converter parameter. - let url = service.getUrlForUri(msgUri); + const url = service.getUrlForUri(msgUri); - let channel = Services.io.newChannelFromURI( + const channel = Services.io.newChannelFromURI( url, null, Services.scriptSecurityManager.getSystemPrincipal(), @@ -51,7 +51,7 @@ function apply_mime_conversion(msgUri, smimeHeaderSink) { channel.QueryInterface(Ci.nsIMailChannel).smimeHeaderSink = smimeHeaderSink; // Make the MIME converter, using the listener we first set up. - let converter = Cc["@mozilla.org/streamConverters;1"] + const converter = Cc["@mozilla.org/streamConverters;1"] .getService(Ci.nsIStreamConverterService) .asyncConvertData("message/rfc822", "text/html", listener, channel); diff --git a/mailnews/news/test/unit/head_server_setup.js b/mailnews/news/test/unit/head_server_setup.js index 6a5bcbda9f..515eb9e723 100644 --- a/mailnews/news/test/unit/head_server_setup.js +++ b/mailnews/news/test/unit/head_server_setup.js @@ -132,14 +132,14 @@ function setupLocalServer(port, host = "localhost") { if (_server != null) { return _server; } - let serverAndAccount = localAccountUtils.create_incoming_server_and_account( + const serverAndAccount = localAccountUtils.create_incoming_server_and_account( "nntp", port, null, null, host ); - let server = serverAndAccount.server; + const server = serverAndAccount.server; subscribeServer(server); _server = server;