Repository: GoogleChrome/lighthouse
Pull request #12450 (2021-05-06 20:07:21)

core(fr): convert js-usage gatherer
Currently split have debugger in sensitive instrumentation and profiler in normal instrumentation. Debugger can pick up on anonymous scripts run by Lighthouse although this gatherer ignores them.

Ref #11313



Patch:
diff --git a/lighthouse-core/fraggle-rock/config/default-config.js b/lighthouse-core/fraggle-rock/config/default-config.js
index e487492f9..38f3eb305 100644
--- a/lighthouse-core/fraggle-rock/config/default-config.js
+++ b/lighthouse-core/fraggle-rock/config/default-config.js
@@ -25,6 +25,7 @@ const artifacts = {
   GlobalListeners: '',
   IFrameElements: '',
   InstallabilityErrors: '',
+  JsUsage: '',
   MetaElements: '',
   NetworkUserAgent: '',
   PasswordInputsWithPreventedPaste: '',
@@ -63,6 +64,7 @@ const defaultConfig = {
     {id: artifacts.GlobalListeners, gatherer: 'global-listeners'},
     {id: artifacts.IFrameElements, gatherer: 'iframe-elements'},
     {id: artifacts.InstallabilityErrors, gatherer: 'installability-errors'},
+    {id: artifacts.JsUsage, gatherer: 'js-usage'},
     {id: artifacts.MetaElements, gatherer: 'meta-elements'},
     {id: artifacts.NetworkUserAgent, gatherer: 'network-user-agent'},
     {id: artifacts.PasswordInputsWithPreventedPaste, gatherer: 'dobetterweb/password-inputs-with-prevented-paste'},
@@ -99,6 +101,7 @@ const defaultConfig = {
         artifacts.GlobalListeners,
         artifacts.IFrameElements,
         artifacts.InstallabilityErrors,
+        artifacts.JsUsage,
         artifacts.MetaElements,
         artifacts.NetworkUserAgent,
         artifacts.PasswordInputsWithPreventedPaste,
diff --git a/lighthouse-core/gather/driver.js b/lighthouse-core/gather/driver.js
index 671e4e36d..69419bd3d 100644
--- a/lighthouse-core/gather/driver.js
+++ b/lighthouse-core/gather/driver.js
@@ -15,8 +15,6 @@ const log = require('lighthouse-logger');
 const DevtoolsLog = require('./devtools-log.js');
 const TraceGatherer = require('./gatherers/trace.js');
 
-const pageFunctions = require('../lib/page-functions.js');
-
 // Pulled in for Connection type checking.
 // eslint-disable-next-line no-unused-vars
 const Connection = require('./connections/connection.js');
@@ -462,39 +460,6 @@ class Driver {
     this._devtoolsLog.endRecording();
     return this._devtoolsLog.messages;
   }
-
-  /**
-   * Use a RequestIdleCallback shim for tests run with simulated throttling, so that the deadline can be used without
-   * a penalty
-   * @param {LH.Config.Settings} settings
-   * @return {Promise<void>}
-   */
-  async registerRequestIdleCallbackWrap(settings) {
-    if (settings.throttlingMethod === 'simulate') {
-      await this.executionContext.evaluateOnNewDocument(
-        pageFunctions.wrapRequestIdleCallback,
-        {args: [settings.throttling.cpuSlowdownMultiplier]}
-      );
-    }
-  }
-
-  /**
-   * Dismiss JavaScript dialogs (alert, confirm, prompt), providing a
-   * generic promptText in case the dialog is a prompt.
-   * @return {Promise<void>}
-   */
-  async dismissJavaScriptDialogs() {
-    this.on('Page.javascriptDialogOpening', data => {
-      log.warn('Driver', `${data.type} dialog opened by the page automatically suppressed.`);
-
-      this.sendCommand('Page.handleJavaScriptDialog', {
-        accept: true,
-        promptText: 'Lighthouse prompt response',
-      }).catch(err => log.warn('Driver', err));
-    });
-
-    await this.sendCommand('Page.enable');
-  }
 }
 
 module.exports = Driver;
diff --git a/lighthouse-core/gather/driver/prepare.js b/lighthouse-core/gather/driver/prepare.js
new file mode 100644
index 000000000..7c8c4eba3
--- /dev/null
+++ b/lighthouse-core/gather/driver/prepare.js
@@ -0,0 +1,177 @@
+/**
+ * @license Copyright 2021 The Lighthouse Authors. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+ */
+'use strict';
+
+const log = require('lighthouse-logger');
+const storage = require('./storage.js');
+const emulation = require('../../lib/emulation.js');
+const pageFunctions = require('../../lib/page-functions.js');
+
+/**
+ * Enables `Debugger` domain to receive async stacktrace information on network request initiators.
+ * This is critical for tracking attribution of tasks and performance simulation accuracy.
+ * @param {LH.Gatherer.FRProtocolSession} session
+ */
+async function enableAsyncStacks(session) {
+  const enable = async () => {
+    await session.sendCommand('Debugger.enable');
+    await session.sendCommand('Debugger.setSkipAllPauses', {skip: true});
+    await session.sendCommand('Debugger.setAsyncCallStackDepth', {maxDepth: 8});
+  };
+
+  // Resume any pauses that make it through `setSkipAllPauses`
+  session.on('Debugger.paused', () => session.sendCommand('Debugger.resume'));
+
+  // `Debugger.setSkipAllPauses` is reset after every navigation, so retrigger it on main frame navigations.
+  // See https://bugs.chromium.org/p/chromium/issues/detail?id=990945&q=setSkipAllPauses&can=2
+  session.on('Page.frameNavigated', event => {
+    if (event.frame.parentId) return;
+    enable().catch(err => log.error('Driver', err));
+  });
+
+  await enable();
+}
+
+/**
+ * Use a RequestIdleCallback shim for tests run with simulated throttling, so that the deadline can be used without
+ * a penalty.
+ * @param {LH.Gatherer.FRTransitionalDriver} driver
+ * @param {LH.Config.Settings} settings
+ * @return {Promise<void>}
+ */
+async function shimRequestIdleCallbackOnNewDocument(driver, settings) {
+  await driver.executionContext.evaluateOnNewDocument(pageFunctions.wrapRequestIdleCallback, {
+    args: [settings.throttling.cpuSlowdownMultiplier],
+  });
+}
+
+/**
+ * Dismiss JavaScript dialogs (alert, confirm, prompt), providing a
+ * generic promptText in case the dialog is a prompt.
+ * @param {LH.Gatherer.FRProtocolSession} session
+ * @return {Promise<void>}
+ */
+async function dismissJavaScriptDialogs(session) {
+  session.on('Page.javascriptDialogOpening', data => {
+    log.warn('Driver', `${data.type} dialog opened by the page automatically suppressed.`);
+
+    session
+      .sendCommand('Page.handleJavaScriptDialog', {
+        accept: true,
+        promptText: 'Lighthouse prompt response',
+      })
+      .catch(err => log.warn('Driver', err));
+  });
+
+  await session.sendCommand('Page.enable');
+}
+
+/**
+ * @param {LH.Gatherer.FRProtocolSession} session
+ * @param {{url: string}} navigation
+ * @return {Promise<{warnings: Array<LH.IcuMessage>}>}
+ */
+async function resetStorageForNavigation(session, navigation) {
+  /** @type {Array<LH.IcuMessage>} */
+  const warnings = [];
+
+  // Reset the storage and warn if there appears to be other important data.
+  const warning = await storage.getImportantStorageWarning(session, navigation.url);
+  if (warning) warnings.push(warning);
+  await storage.clearDataForOrigin(session, navigation.url);
+  await storage.clearBrowserCaches(session);
+
+  return {warnings};
+}
+
+/**
+ * Prepares a target for a particular navigation by resetting storage and setting throttling.
+ *
+ * This method assumes `prepareTargetForNavigationMode` has already been invoked.
+ *
+ * @param {LH.Gatherer.FRProtocolSession} session
+ * @param {LH.Config.Settings} settings
+ * @param {Pick<LH.Config.NavigationDefn, 'disableThrottling'|'disableStorageReset'|'blockedUrlPatterns'> & {url: string}} navigation
+ */
+async function prepareNetworkForNavigation(session, settings, navigation) {
+  const status = {msg: 'Preparing network conditions', id: `lh:gather:prepareNetworkForNavigation`};
+  log.time(status);
+
+  if (navigation.disableThrottling) await emulation.clearThrottling(session);
+  else await emulation.throttle(session, settings);
+
+  // Set request blocking before any network activity.
+  // No "clearing" is done at the end of the navigation since Network.setBlockedURLs([]) will unset all if
+  // neccessary at the beginning of the next navigation.
+  const blockedUrls = (navigation.blockedUrlPatterns || []).concat(
+    settings.blockedUrlPatterns || []
+  );
+  await session.sendCommand('Network.setBlockedURLs', {urls: blockedUrls});
+
+  const headers = settings.extraHeaders;
+  if (headers) await session.sendCommand('Network.setExtraHTTPHeaders', {headers});
+
+  log.timeEnd(status);
+}
+
+/**
+ * Prepares a target to be analyzed in navigation mode by enabling protocol domains, emulation, and new document
+ * handlers for global APIs or error handling.
+ *
+ * This method should be used in combination with `prepareTargetForIndividualNavigation` before a specific navigation occurs.
+ *
+ * @param {LH.Gatherer.FRTransitionalDriver} driver
+ * @param {LH.Config.Settings} settings
+ */
+async function prepareTargetForNavigationMode(driver, settings) {
+  // Emulate our target device screen and user agent.
+  await emulation.emulate(driver.defaultSession, settings);
+
+  // Enable better stacks on network requests.
+  await enableAsyncStacks(driver.defaultSession);
+
+  // Automatically handle any JavaScript dialogs to prevent a hung renderer.
+  await dismissJavaScriptDialogs(driver.defaultSession);
+
+  // Inject our snippet to cache important web platform APIs before they're (possibly) ponyfilled by the page.
+  await driver.executionContext.cacheNativesOnNewDocument();
+
+  // Wrap requestIdleCallback so pages under simulation receive the correct rIC deadlines.
+  if (settings.throttlingMethod === 'simulate') {
+    await shimRequestIdleCallbackOnNewDocument(driver, settings);
+  }
+}
+
+/**
+ * Prepares a target for a particular navigation by resetting storage and setting network.
+ *
+ * This method assumes `prepareTargetForNavigationMode` has already been invoked.
+ *
+ * @param {LH.Gatherer.FRProtocolSession} session
+ * @param {LH.Config.Settings} settings
+ * @param {Pick<LH.Config.NavigationDefn, 'disableThrottling'|'disableStorageReset'|'blockedUrlPatterns'> & {url: string}} navigation
+ * @return {Promise<{warnings: Array<LH.IcuMessage>}>}
+ */
+async function prepareTargetForIndividualNavigation(session, settings, navigation) {
+  /** @type {Array<LH.IcuMessage>} */
+  const warnings = [];
+
+  const shouldResetStorage = !settings.disableStorageReset && !navigation.disableStorageReset;
+  if (shouldResetStorage) {
+    const {warnings: storageWarnings} = await resetStorageForNavigation(session, navigation);
+    warnings.push(...storageWarnings);
+  }
+
+  await prepareNetworkForNavigation(session, settings, navigation);
+
+  return {warnings};
+}
+
+module.exports = {
+  prepareNetworkForNavigation,
+  prepareTargetForNavigationMode,
+  prepareTargetForIndividualNavigation,
+};
diff --git a/lighthouse-core/gather/driver/storage.js b/lighthouse-core/gather/driver/storage.js
index 4e47c856f..0aa5ac267 100644
--- a/lighthouse-core/gather/driver/storage.js
+++ b/lighthouse-core/gather/driver/storage.js
@@ -100,8 +100,8 @@ async function getImportantStorageWarning(session, url) {
  * @param {LH.Gatherer.FRProtocolSession} session
  * @return {Promise<void>}
  */
-async function cleanBrowserCaches(session) {
-  const status = {msg: 'Cleaning browser cache', id: 'lh:storage:cleanBrowserCaches'};
+async function clearBrowserCaches(session) {
+  const status = {msg: 'Cleaning browser cache', id: 'lh:storage:clearBrowserCaches'};
   log.time(status);
 
   // Wipe entire disk cache
@@ -115,7 +115,7 @@ async function cleanBrowserCaches(session) {
 
 module.exports = {
   clearDataForOrigin,
-  cleanBrowserCaches,
+  clearBrowserCaches,
   getImportantStorageWarning,
   UIStrings,
 };
diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js
index 53010dac5..9d10478f7 100644
--- a/lighthouse-core/gather/gather-runner.js
+++ b/lighthouse-core/gather/gather-runner.js
@@ -14,6 +14,7 @@ const constants = require('../config/constants.js');
 const i18n = require('../lib/i18n/i18n.js');
 const URL = require('../lib/url-shim.js');
 const {getBenchmarkIndex} = require('./driver/environment.js');
+const prepare = require('./driver/prepare.js');
 const storage = require('./driver/storage.js');
 const navigation = require('./driver/navigation.js');
 const serviceWorkers = require('./driver/service-workers.js');
@@ -174,46 +175,19 @@ class GatherRunner {
   /**
    * @param {Driver} driver
    * @param {{requestedUrl: string, settings: LH.Config.Settings}} options
-   * @param {(string | LH.IcuMessage)[]} LighthouseRunWarnings
    * @return {Promise<void>}
    */
-  static async setupDriver(driver, options, LighthouseRunWarnings) {
+  static async setupDriver(driver, options) {
     const status = {msg: 'Initializing…', id: 'lh:gather:setupDriver'};
     log.time(status);
-    const resetStorage = !options.settings.disableStorageReset;
     const session = driver.defaultSession;
 
     // Assert no service workers are still installed, so we test that they would actually be installed for a new user.
     // TODO(FR-COMPAT): re-evaluate the necessity of this check
     await GatherRunner.assertNoSameOriginServiceWorkerClients(session, options.requestedUrl);
 
-    // Emulate our target device screen and user agent.
-    await emulation.emulate(driver.defaultSession, options.settings);
+    await prepare.prepareTargetForNavigationMode(driver, options.settings);
 
-    // Enable `Debugger` domain to receive async stacktrace information on network request initiators.
-    // This is critical for tracing certain performance simulation situations.
-    session.on('Debugger.paused', () => session.sendCommand('Debugger.resume'));
-    await session.sendCommand('Debugger.enable');
-    await session.sendCommand('Debugger.setSkipAllPauses', {skip: true});
-    await session.sendCommand('Debugger.setAsyncCallStackDepth', {maxDepth: 8});
-
-    // Inject our snippet to cache important web platform APIs before they're (possibly) ponyfilled by the page.
-    await driver.executionContext.cacheNativesOnNewDocument();
-
-    // Automatically handle any JavaScript dialogs to prevent a hung renderer.
-    await driver.dismissJavaScriptDialogs();
-
-    // Wrap requestIdleCallback so pages under simulation receive the correct rIC deadlines.
-    await driver.registerRequestIdleCallbackWrap(options.settings);
-
-    // Reset the storage and warn if there appears to be other important data.
-    if (resetStorage) {
-      const warning = await storage.getImportantStorageWarning(session, options.requestedUrl);
-      if (warning) {
-        LighthouseRunWarnings.push(warning);
-      }
-      await storage.clearDataForOrigin(session, options.requestedUrl);
-    }
     log.timeEnd(status);
   }
 
@@ -407,35 +381,6 @@ class GatherRunner {
     return str_(UIStrings.warningSlowHostCpu);
   }
 
-  /**
-   * Initialize network settings for the pass, e.g. throttling, blocked URLs,
-   * and manual request headers.
-   * @param {LH.Gatherer.PassContext} passContext
-   * @return {Promise<void>}
-   */
-  static async setupPassNetwork(passContext) {
-    const status = {msg: 'Setting up network for the pass trace', id: `lh:gather:setupPassNetwork`};
-    log.time(status);
-
-    const session = passContext.driver.defaultSession;
-    const passConfig = passContext.passConfig;
-    if (passConfig.useThrottling) await emulation.throttle(session, passContext.settings);
-    else await emulation.clearThrottling(session);
-
-    const blockedUrls = (passContext.passConfig.blockedUrlPatterns || [])
-      .concat(passContext.settings.blockedUrlPatterns || []);
-
-    // Set request blocking before any network activity
-    // No "clearing" is done at the end of the pass since Network.setBlockedURLs([]) will unset all if
-    // neccessary at the beginning of the next pass.
-    await session.sendCommand('Network.setBlockedURLs', {urls: blockedUrls});
-
-    const headers = passContext.settings.extraHeaders;
-    if (headers) await session.sendCommand('Network.setExtraHTTPHeaders', {headers});
-
-    log.timeEnd(status);
-  }
-
   /**
    * Beging recording devtoolsLog and trace (if requested).
    * @param {LH.Gatherer.PassContext} passContext
@@ -728,7 +673,7 @@ class GatherRunner {
       const baseArtifacts = await GatherRunner.initializeBaseArtifacts(options);
       baseArtifacts.BenchmarkIndex = await getBenchmarkIndex(driver.executionContext);
 
-      await GatherRunner.setupDriver(driver, options, baseArtifacts.LighthouseRunWarnings);
+      await GatherRunner.setupDriver(driver, options);
 
       let isFirstPass = true;
       for (const passConfig of passConfigs) {
@@ -774,17 +719,6 @@ class GatherRunner {
     }
   }
 
-  /**
-   * Returns whether this pass should clear the caches.
-   * Only if it is a performance run and the settings don't disable it.
-   * @param {LH.Gatherer.PassContext} passContext
-   * @return {boolean}
-   */
-  static shouldClearCaches(passContext) {
-    const {settings, passConfig} = passContext;
-    return !settings.disableStorageReset && passConfig.recordTrace && passConfig.useThrottling;
-  }
-
   /**
    * Save the devtoolsLog and trace (if applicable) to baseArtifacts.
    * @param {LH.Gatherer.PassContext} passContext
@@ -816,10 +750,17 @@ class GatherRunner {
 
     // Go to about:blank, set up, and run `beforePass()` on gatherers.
     await GatherRunner.loadBlank(driver, passConfig.blankPage);
-    await GatherRunner.setupPassNetwork(passContext);
-    if (GatherRunner.shouldClearCaches(passContext)) {
-      await storage.cleanBrowserCaches(driver.defaultSession); // Clear disk & memory cache if it's a perf run
-    }
+    const {warnings} = await prepare.prepareTargetForIndividualNavigation(
+      driver.defaultSession,
+      passContext.settings,
+      {
+        url: passContext.url,
+        disableStorageReset: !passConfig.useThrottling,
+        disableThrottling: !passConfig.useThrottling,
+        blockedUrlPatterns: passConfig.blockedUrlPatterns,
+      }
+    );
+    passContext.LighthouseRunWarnings.push(...warnings);
     await GatherRunner.beforePass(passContext, gathererResults);
 
     // Navigate, start recording, and run `pass()` on gatherers.
diff --git a/lighthouse-core/gather/gatherers/js-usage.js b/lighthouse-core/gather/gatherers/js-usage.js
index 09d11c85a..62b3f7359 100644
--- a/lighthouse-core/gather/gatherers/js-usage.js
+++ b/lighthouse-core/gather/gatherers/js-usage.js
@@ -5,16 +5,24 @@
  */
 'use strict';
 
-const Gatherer = require('./gatherer.js');
+const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js');
 
 /**
  * @fileoverview Tracks unused JavaScript
  */
-class JsUsage extends Gatherer {
+class JsUsage extends FRGatherer {
+  /** @type {LH.Gatherer.GathererMeta} */
+  meta = {
+    // TODO(FR-COMPAT): special snapshot case for scriptId -> URL mappings.
+    supportedModes: ['timespan', 'navigation'],
+  }
+
   constructor() {
     super();
     /** @type {LH.Crdp.Debugger.ScriptParsedEvent[]} */
     this._scriptParsedEvents = [];
+    /** @type {LH.Crdp.Profiler.ScriptCoverage[]} */
+    this._scriptUsages = [];
     this.onScriptParsed = this.onScriptParsed.bind(this);
   }
 
@@ -28,33 +36,50 @@ class JsUsage extends Gatherer {
   }
 
   /**
-   * @param {LH.Gatherer.PassContext} passContext
+   * @param {LH.Gatherer.FRTransitionalContext} context
    */
-  async beforePass(passContext) {
-    await passContext.driver.sendCommand('Profiler.enable');
-    await passContext.driver.sendCommand('Profiler.startPreciseCoverage', {detailed: false});
-
-    await passContext.driver.sendCommand('Debugger.enable');
-    await passContext.driver.on('Debugger.scriptParsed', this.onScriptParsed);
+  async startInstrumentation(context) {
+    const session = context.driver.defaultSession;
+    await session.sendCommand('Profiler.enable');
+    await session.sendCommand('Profiler.startPreciseCoverage', {detailed: false});
   }
 
   /**
-   * @param {LH.Gatherer.PassContext} passContext
-   * @return {Promise<LH.Artifacts['JsUsage']>}
+   * @param {LH.Gatherer.FRTransitionalContext} context
    */
-  async afterPass(passContext) {
-    const driver = passContext.driver;
+  async stopInstrumentation(context) {
+    const session = context.driver.defaultSession;
+    const coverageResponse = await session.sendCommand('Profiler.takePreciseCoverage');
+    this._scriptUsages = coverageResponse.result;
+    await session.sendCommand('Profiler.stopPreciseCoverage');
+    await session.sendCommand('Profiler.disable');
+  }
 
-    const coverageResponse = await driver.sendCommand('Profiler.takePreciseCoverage');
-    const scriptUsages = coverageResponse.result;
-    await driver.sendCommand('Profiler.stopPreciseCoverage');
-    await driver.sendCommand('Profiler.disable');
+  /**
+   * @param {LH.Gatherer.FRTransitionalContext} context
+   */
+  async startSensitiveInstrumentation(context) {
+    const session = context.driver.defaultSession;
+    await session.sendCommand('Debugger.enable');
+    await session.on('Debugger.scriptParsed', this.onScriptParsed);
+  }
 
-    await passContext.driver.sendCommand('Debugger.disable');
+  /**
+   * @param {LH.Gatherer.FRTransitionalContext} context
+   */
+  async stopSensitiveInstrumentation(context) {
+    const session = context.driver.defaultSession;
+    await session.off('Debugger.scriptParsed', this.onScriptParsed);
+    await session.sendCommand('Debugger.disable');
+  }
 
+  /**
+   * @return {Promise<LH.Artifacts['JsUsage']>}
+   */
+  async getArtifact() {
     /** @type {Record<string, Array<LH.Crdp.Profiler.ScriptCoverage>>} */
     const usageByUrl = {};
-    for (const scriptUsage of scriptUsages) {
+    for (const scriptUsage of this._scriptUsages) {
       // `ScriptCoverage.url` can be overridden by a magic sourceURL comment.
       // Get the associated ScriptParsedEvent and use embedderName, which is the original url.
       // See https://chromium-review.googlesource.com/c/v8/v8/+/2317310
@@ -67,7 +92,7 @@ class JsUsage extends Gatherer {
 
       // If `url` is blank, that means the script was anonymous (eval, new Function, onload, ...).
       // Or, it's because it was code Lighthouse over the protocol via `Runtime.evaluate`.
-      // We currently don't consider coverage of anonymous scripts, and we defintelty don't want
+      // We currently don't consider coverage of anonymous scripts, and we definitely don't want
       // coverage of code Lighthouse ran to inspect the page, so we ignore this ScriptCoverage if
       // url is blank.
       if (scriptUsage.url === '' || (scriptParsedEvent && scriptParsedEvent.embedderName === '')) {
diff --git a/types/artifacts.d.ts b/types/artifacts.d.ts
index f2c81cd18..b9a45a342 100644
--- a/types/artifacts.d.ts
+++ b/types/artifacts.d.ts
@@ -26,7 +26,6 @@ declare global {
       | 'HTTPRedirect'
       | 'ImageElements'
       | 'InspectorIssues'
-      | 'JsUsage'
       | 'LinkElements'
       | 'MainDocumentContent'
       | 'Manifest'


Test patch:
diff --git a/lighthouse-core/test/fraggle-rock/api-test-pptr.js b/lighthouse-core/test/fraggle-rock/api-test-pptr.js
index 5f60136cb..47ee0d6fc 100644
--- a/lighthouse-core/test/fraggle-rock/api-test-pptr.js
+++ b/lighthouse-core/test/fraggle-rock/api-test-pptr.js
@@ -159,7 +159,7 @@ describe('Fraggle Rock API', () => {
       const {lhr} = result;
       const {auditResults, failedAudits, erroredAudits} = getAuditsBreakdown(lhr);
       // TODO(FR-COMPAT): This assertion can be removed when full compatibility is reached.
-      expect(auditResults.length).toMatchInlineSnapshot(`105`);
+      expect(auditResults.length).toMatchInlineSnapshot(`106`);
       expect(erroredAudits).toHaveLength(0);
 
       const failedAuditIds = failedAudits.map(audit => audit.id);
diff --git a/lighthouse-core/test/fraggle-rock/gather/mock-driver.js b/lighthouse-core/test/fraggle-rock/gather/mock-driver.js
index 80c199007..db1e07141 100644
--- a/lighthouse-core/test/fraggle-rock/gather/mock-driver.js
+++ b/lighthouse-core/test/fraggle-rock/gather/mock-driver.js
@@ -73,8 +73,18 @@ function createMockPage() {
 }
 
 function createMockExecutionContext() {
-  const context = /** @type {ExecutionContext} */ ({});
-  return {...context, evaluate: jest.fn(), evaluateAsync: jest.fn()};
+  return {
+    evaluate: jest.fn(),
+    evaluateAsync: jest.fn(),
+    evaluateOnNewDocument: jest.fn(),
+    cacheNativesOnNewDocument: jest.fn(),
+
+    /** @return {ExecutionContext} */
+    asExecutionContext() {
+      // @ts-expect-error - We'll rely on the tests passing to know this matches.
+      return this;
+    },
+  };
 }
 
 function createMockDriver() {
@@ -89,7 +99,7 @@ function createMockDriver() {
     url: () => page.url(),
     defaultSession: session,
     connect: jest.fn(),
-    executionContext: context,
+    executionContext: context.asExecutionContext(),
 
     /** @return {Driver} */
     asDriver() {
diff --git a/lighthouse-core/test/gather/driver/prepare-test.js b/lighthouse-core/test/gather/driver/prepare-test.js
new file mode 100644
index 000000000..c58f218b6
--- /dev/null
+++ b/lighthouse-core/test/gather/driver/prepare-test.js
@@ -0,0 +1,340 @@
+/**
+ * @license Copyright 2021 The Lighthouse Authors. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+ */
+'use strict';
+
+/* eslint-env jest */
+
+const storageMock = {
+  clearDataForOrigin: jest.fn(),
+  clearBrowserCaches: jest.fn(),
+  getImportantStorageWarning: jest.fn(),
+};
+jest.mock('../../../gather/driver/storage.js', () => storageMock);
+
+const {createMockSession, createMockDriver} = require('../../fraggle-rock/gather/mock-driver.js');
+const {flushAllTimersAndMicrotasks} = require('../../test-utils.js');
+const prepare = require('../../../gather/driver/prepare.js');
+const constants = require('../../../config/constants.js');
+
+const url = 'https://example.com';
+let sessionMock = createMockSession();
+
+beforeEach(() => {
+  sessionMock = createMockSession();
+  sessionMock.sendCommand
+    .mockResponse('Network.emulateNetworkConditions')
+    .mockResponse('Emulation.setCPUThrottlingRate')
+    .mockResponse('Network.setBlockedURLs')
+    .mockResponse('Network.setExtraHTTPHeaders');
+  storageMock.clearBrowserCaches = jest.fn();
+  storageMock.clearDataForOrigin = jest.fn();
+  storageMock.getImportantStorageWarning = jest.fn();
+});
+
+afterEach(() => {
+  jest.useRealTimers();
+});
+
+describe('.prepareNetworkForNavigation()', () => {
+  it('sets throttling appropriately', async () => {
+    await prepare.prepareNetworkForNavigation(
+      sessionMock.asSession(),
+      {
+        ...constants.defaultSettings,
+        throttlingMethod: 'devtools',
+        throttling: {
+          ...constants.defaultSettings.throttling,
+          requestLatencyMs: 100,
+          downloadThroughputKbps: 8,
+          uploadThroughputKbps: 8,
+          cpuSlowdownMultiplier: 2,
+        },
+      },
+      {
+        ...constants.defaultNavigationConfig,
+        url,
+      }
+    );
+
+    expect(sessionMock.sendCommand.findInvocation('Network.emulateNetworkConditions')).toEqual({
+      latency: 100,
+      downloadThroughput: 1024,
+      uploadThroughput: 1024,
+      offline: false,
+    });
+    expect(sessionMock.sendCommand.findInvocation('Emulation.setCPUThrottlingRate')).toEqual({
+      rate: 2,
+    });
+  });
+
+  it('disables throttling', async () => {
+    await prepare.prepareNetworkForNavigation(
+      sessionMock.asSession(),
+      {
+        ...constants.defaultSettings,
+        throttlingMethod: 'devtools',
+        throttling: {
+          ...constants.defaultSettings.throttling,
+          requestLatencyMs: 100,
+          downloadThroughputKbps: 8,
+          uploadThroughputKbps: 8,
+          cpuSlowdownMultiplier: 2,
+        },
+      },
+      {
+        ...constants.defaultNavigationConfig,
+        url,
+        disableThrottling: true,
+      }
+    );
+
+    expect(sessionMock.sendCommand.findInvocation('Network.emulateNetworkConditions')).toEqual({
+      latency: 0,
+      downloadThroughput: 0,
+      uploadThroughput: 0,
+      offline: false,
+    });
+    expect(sessionMock.sendCommand.findInvocation('Emulation.setCPUThrottlingRate')).toEqual({
+      rate: 1,
+    });
+  });
+
+  it('unsets url patterns when empty', async () => {
+    await prepare.prepareNetworkForNavigation(
+      sessionMock.asSession(),
+      {
+        ...constants.defaultSettings,
+        blockedUrlPatterns: null,
+      },
+      {
+        ...constants.defaultNavigationConfig,
+        blockedUrlPatterns: [],
+        url,
+      }
+    );
+
+    expect(sessionMock.sendCommand.findInvocation('Network.setBlockedURLs')).toEqual({
+      urls: [],
+    });
+  });
+
+  it('blocks url patterns', async () => {
+    await prepare.prepareNetworkForNavigation(
+      sessionMock.asSession(),
+      {
+        ...constants.defaultSettings,
+        blockedUrlPatterns: ['https://a.example.com'],
+      },
+      {
+        ...constants.defaultNavigationConfig,
+        blockedUrlPatterns: ['https://b.example.com'],
+        url,
+      }
+    );
+
+    expect(sessionMock.sendCommand.findInvocation('Network.setBlockedURLs')).toEqual({
+      urls: ['https://b.example.com', 'https://a.example.com'],
+    });
+  });
+
+  it('sets extraHeaders', async () => {
+    await prepare.prepareNetworkForNavigation(
+      sessionMock.asSession(),
+      {...constants.defaultSettings, extraHeaders: {'Cookie': 'monster', 'x-men': 'wolverine'}},
+      {...constants.defaultNavigationConfig, url}
+    );
+
+    expect(sessionMock.sendCommand.findInvocation('Network.setExtraHTTPHeaders')).toEqual({
+      headers: {
+        'Cookie': 'monster',
+        'x-men': 'wolverine',
+      },
+    });
+  });
+});
+
+describe('.prepareTargetForIndividualNavigation()', () => {
+  it('clears storage when not disabled', async () => {
+    await prepare.prepareTargetForIndividualNavigation(
+      sessionMock.asSession(),
+      {...constants.defaultSettings, disableStorageReset: false},
+      {...constants.defaultNavigationConfig, disableStorageReset: false, url}
+    );
+
+    expect(storageMock.clearDataForOrigin).toHaveBeenCalled();
+    expect(storageMock.clearBrowserCaches).toHaveBeenCalled();
+  });
+
+  it('does not clear storage when globally disabled', async () => {
+    await prepare.prepareTargetForIndividualNavigation(
+      sessionMock.asSession(),
+      {...constants.defaultSettings, disableStorageReset: true},
+      {...constants.defaultNavigationConfig, disableStorageReset: false, url}
+    );
+
+    expect(storageMock.clearDataForOrigin).not.toHaveBeenCalled();
+    expect(storageMock.clearBrowserCaches).not.toHaveBeenCalled();
+  });
+
+  it('does not clear storage when disabled per navigation', async () => {
+    await prepare.prepareTargetForIndividualNavigation(
+      sessionMock.asSession(),
+      {...constants.defaultSettings, disableStorageReset: false},
+      {...constants.defaultNavigationConfig, disableStorageReset: true, url}
+    );
+
+    expect(storageMock.clearDataForOrigin).not.toHaveBeenCalled();
+    expect(storageMock.clearBrowserCaches).not.toHaveBeenCalled();
+  });
+
+  it('collects storage warnings', async () => {
+    storageMock.getImportantStorageWarning.mockResolvedValue({message: 'This is a warning'});
+    const {warnings} = await prepare.prepareTargetForIndividualNavigation(
+      sessionMock.asSession(),
+      {...constants.defaultSettings, disableStorageReset: false},
+      {...constants.defaultNavigationConfig, disableStorageReset: false, url}
+    );
+
+    expect(warnings).toEqual([{message: 'This is a warning'}]);
+  });
+});
+
+describe('.prepareTargetForNavigationMode()', () => {
+  let driverMock = createMockDriver();
+
+  beforeEach(() => {
+    driverMock = createMockDriver();
+    sessionMock = driverMock._session;
+
+    sessionMock.sendCommand
+      .mockResponse('Network.enable')
+      .mockResponse('Network.setUserAgentOverride')
+      .mockResponse('Emulation.setDeviceMetricsOverride')
+      .mockResponse('Emulation.setTouchEmulationEnabled')
+      .mockResponse('Debugger.enable')
+      .mockResponse('Debugger.setSkipAllPauses')
+      .mockResponse('Debugger.setAsyncCallStackDepth')
+      .mockResponse('Page.enable');
+  });
+
+  it('emulates the target device', async () => {
+    await prepare.prepareTargetForNavigationMode(driverMock.asDriver(), {
+      ...constants.defaultSettings,
+      screenEmulation: {
+        disabled: false,
+        mobile: true,
+        deviceScaleFactor: 2,
+        width: 200,
+        height: 300,
+      },
+    });
+
+    expect(sessionMock.sendCommand.findInvocation('Emulation.setDeviceMetricsOverride')).toEqual({
+      mobile: true,
+      deviceScaleFactor: 2,
+      width: 200,
+      height: 300,
+    });
+  });
+
+  it('enables async stacks', async () => {
+    await prepare.prepareTargetForNavigationMode(driverMock.asDriver(), {
+      ...constants.defaultSettings,
+    });
+
+    const invocations = sessionMock.sendCommand.mock.calls;
+    const debuggerInvocations = invocations.filter(call => call[0].startsWith('Debugger.'));
+    expect(debuggerInvocations.map(argList => argList[0])).toEqual([
+      'Debugger.enable',
+      'Debugger.setSkipAllPauses',
+      'Debugger.setAsyncCallStackDepth',
+    ]);
+  });
+
+  it('enables async stacks on every main frame navigation', async () => {
+    jest.useFakeTimers();
+
+    sessionMock.sendCommand
+      .mockResponse('Debugger.enable')
+      .mockResponse('Debugger.setSkipAllPauses')
+      .mockResponse('Debugger.setAsyncCallStackDepth');
+
+    sessionMock.on.mockEvent('Page.frameNavigated', {frame: {}});
+    sessionMock.on.mockEvent('Page.frameNavigated', {frame: {parentId: '1'}});
+    sessionMock.on.mockEvent('Page.frameNavigated', {frame: {parentId: '2'}});
+    sessionMock.on.mockEvent('Page.frameNavigated', {frame: {parentId: '3'}});
+
+    await prepare.prepareTargetForNavigationMode(driverMock.asDriver(), {
+      ...constants.defaultSettings,
+    });
+
+    await flushAllTimersAndMicrotasks();
+
+    const invocations = sessionMock.sendCommand.mock.calls;
+    const debuggerInvocations = invocations.filter(call => call[0].startsWith('Debugger.'));
+    expect(debuggerInvocations.map(argList => argList[0])).toEqual([
+      'Debugger.enable',
+      'Debugger.setSkipAllPauses',
+      'Debugger.setAsyncCallStackDepth',
+      'Debugger.enable',
+      'Debugger.setSkipAllPauses',
+      'Debugger.setAsyncCallStackDepth',
+    ]);
+  });
+
+  it('cache natives on new document', async () => {
+    await prepare.prepareTargetForNavigationMode(driverMock.asDriver(), {
+      ...constants.defaultSettings,
+    });
+
+    expect(driverMock._executionContext.cacheNativesOnNewDocument).toHaveBeenCalled();
+  });
+
+  it('install rIC shim on simulated throttling', async () => {
+    await prepare.prepareTargetForNavigationMode(driverMock.asDriver(), {
+      ...constants.defaultSettings,
+      throttlingMethod: 'simulate',
+    });
+
+    const invocations = driverMock._executionContext.evaluateOnNewDocument.mock.calls;
+    if (!invocations.length) expect(invocations).toHaveLength(1);
+    const matchingInvocations = invocations.filter(argList =>
+      argList[0].toString().includes('requestIdleCallback')
+    );
+    if (!matchingInvocations.length) expect(invocations).toContain('An item shimming rIC');
+  });
+
+  it('not install rIC shim on devtools throttling', async () => {
+    await prepare.prepareTargetForNavigationMode(driverMock.asDriver(), {
+      ...constants.defaultSettings,
+      throttlingMethod: 'devtools',
+    });
+
+    const invocations = driverMock._executionContext.evaluateOnNewDocument.mock.calls;
+    const matchingInvocations = invocations.filter(argList =>
+      argList[0].toString().includes('requestIdleCallback')
+    );
+    expect(matchingInvocations).toHaveLength(0);
+  });
+
+  it('handle javascript dialogs automatically', async () => {
+    jest.useFakeTimers();
+
+    sessionMock.sendCommand.mockResponse('Page.handleJavaScriptDialog');
+    sessionMock.on.mockEvent('Page.javascriptDialogOpening', {type: 'confirm'});
+
+    await prepare.prepareTargetForNavigationMode(driverMock.asDriver(), {
+      ...constants.defaultSettings,
+    });
+
+    await flushAllTimersAndMicrotasks();
+
+    expect(sessionMock.sendCommand).toHaveBeenCalledWith('Page.handleJavaScriptDialog', {
+      accept: true,
+      promptText: 'Lighthouse prompt response',
+    });
+  });
+});
diff --git a/lighthouse-core/test/gather/gather-runner-test.js b/lighthouse-core/test/gather/gather-runner-test.js
index 81886aa39..60b7a6460 100644
--- a/lighthouse-core/test/gather/gather-runner-test.js
+++ b/lighthouse-core/test/gather/gather-runner-test.js
@@ -13,7 +13,6 @@ const Gatherer = require('../../gather/gatherers/gatherer.js');
 const GatherRunner_ = require('../../gather/gather-runner.js');
 const assert = require('assert').strict;
 const Config = require('../../config/config.js');
-const constants = require('../../config/constants.js');
 const unresolvedPerfLog = require('./../fixtures/unresolved-perflog.json');
 const NetworkRequest = require('../../lib/network-request.js');
 const LHError = require('../../lib/lh-error.js');
@@ -42,7 +41,6 @@ const GatherRunner = {
   run: makeParamsOptional(GatherRunner_.run),
   runPass: makeParamsOptional(GatherRunner_.runPass),
   setupDriver: makeParamsOptional(GatherRunner_.setupDriver),
-  setupPassNetwork: makeParamsOptional(GatherRunner_.setupPassNetwork),
   // Spies that should have mock implemenations most of the time.
   assertNoSameOriginServiceWorkerClients: jest.spyOn(GatherRunner_,
     'assertNoSameOriginServiceWorkerClients'),
@@ -124,17 +122,6 @@ function resetDefaultMockResponses() {
     .mockResponse('ServiceWorker.enable');
 }
 
-/**
- * Restore the emulation to its original implementation for testing emulation-sensitive logic.
- */
-function restoreActualEmulation() {
-  const actualEmulation = jest.requireActual('../../lib/emulation.js');
-  const emulation = require('../../lib/emulation.js');
-  emulation.emulate = actualEmulation.emulate;
-  emulation.throttle = actualEmulation.throttle;
-  emulation.clearThrottling = actualEmulation.clearThrottling;
-}
-
 beforeEach(() => {
   jest.useFakeTimers();
   // @ts-expect-error - connectionStub has a mocked version of sendCommand implemented in each test
@@ -151,8 +138,9 @@ beforeEach(() => {
   emulation.throttle = jest.fn();
   emulation.clearThrottling = jest.fn();
 
-  const storage = require('../../gather/driver/storage.js');
-  storage.clearDataForOrigin = jest.fn();
+  const prepare = require('../../gather/driver/prepare.js');
+  prepare.prepareTargetForNavigationMode = jest.fn();
+  prepare.prepareTargetForIndividualNavigation = jest.fn().mockResolvedValue({warnings: []});
 
   const navigation = jest.requireMock('../../gather/driver/navigation.js');
   navigation.gotoURL = jest.fn().mockResolvedValue({finalUrl: 'https://example.com'});
@@ -284,31 +272,6 @@ describe('GatherRunner', function() {
     test('works when running on desktop device', DESKTOP_UA, 'desktop');
   });
 
-  /** @param {NonNullable<LH.SharedFlagsSettings['formFactor']>}formFactor */
-  const getSettings = formFactor => ({
-    formFactor: formFactor,
-    screenEmulation: constants.screenEmulationMetrics[formFactor],
-  });
-
-  it('sets up the driver to begin emulation when all flags are undefined', async () => {
-    restoreActualEmulation();
-    await GatherRunner.setupDriver(driver, {settings: getSettings('mobile')});
-
-    connectionStub.sendCommand.findInvocation('Emulation.setDeviceMetricsOverride');
-  });
-
-  it('applies the correct emulation given a particular formFactor', async () => {
-    restoreActualEmulation();
-    await GatherRunner.setupDriver(driver, {settings: getSettings('mobile')});
-    expect(connectionStub.sendCommand.findInvocation('Emulation.setDeviceMetricsOverride'))
-      .toMatchObject({mobile: true});
-
-    resetDefaultMockResponses();
-    await GatherRunner.setupDriver(driver, {settings: getSettings('desktop')});
-    expect(connectionStub.sendCommand.findInvocation('Emulation.setDeviceMetricsOverride'))
-      .toMatchObject({mobile: false});
-  });
-
   describe('.assertNoSameOriginServiceWorkerClients', () => {
     /** @type {LH.Gatherer.FRProtocolSession} */
     let session;
@@ -447,19 +410,7 @@ describe('GatherRunner', function() {
     });
   });
 
-  it('clears origin storage', async () => {
-    const storage = jest.requireMock('../../gather/driver/storage.js');
-    await GatherRunner.setupDriver(driver, {settings: {}});
-    expect(storage.clearDataForOrigin).toHaveBeenCalled();
-  });
-
-  it('does not clear origin storage with flag --disable-storage-reset', async () => {
-    const storage = jest.requireMock('../../gather/driver/storage.js');
-    await GatherRunner.setupDriver(driver, {settings: {disableStorageReset: true}});
-    expect(storage.clearDataForOrigin).not.toHaveBeenCalled();
-  });
-
-  it('clears the disk & memory cache on a perf run', async () => {
+  it('prepares target for navigation', async () => {
     const passConfig = {
       passName: 'default',
       loadFailureMode: LoadFailureMode.ignore,
@@ -476,11 +427,12 @@ describe('GatherRunner', function() {
       passConfig,
       settings,
       baseArtifacts: await GatherRunner.initializeBaseArtifacts({driver, settings, requestedUrl}),
+      LighthouseRunWarnings: [],
     };
 
-    const storage = jest.requireMock('../../gather/driver/storage.js');
+    const prepare = jest.requireMock('../../gather/driver/prepare.js');
     await GatherRunner.runPass(passContext);
-    expect(storage.cleanBrowserCaches).toHaveBeenCalled();
+    expect(prepare.prepareTargetForIndividualNavigation).toHaveBeenCalled();
   });
 
   it('returns a pageLoadError and no artifacts when there is a network error', async () => {
@@ -600,111 +552,6 @@ describe('GatherRunner', function() {
     expect(artifacts.devtoolsLogs).toHaveProperty('pageLoadError-nextPass');
   });
 
-  it('sets throttling appropriately', async () => {
-    restoreActualEmulation();
-    await GatherRunner.setupPassNetwork({
-      driver,
-      settings: {
-        formFactor: 'mobile',
-        screenEmulation: constants.screenEmulationMetrics.mobile,
-        throttlingMethod: 'devtools',
-        throttling: {
-          requestLatencyMs: 100,
-          downloadThroughputKbps: 8,
-          uploadThroughputKbps: 8,
-          cpuSlowdownMultiplier: 2,
-        },
-      },
-      passConfig: {
-        useThrottling: true,
-        gatherers: [],
-      },
-    });
-
-    expect(connectionStub.sendCommand.findInvocation('Network.emulateNetworkConditions')).toEqual({
-      latency: 100, downloadThroughput: 1024, uploadThroughput: 1024, offline: false,
-    });
-    expect(connectionStub.sendCommand.findInvocation('Emulation.setCPUThrottlingRate')).toEqual({
-      rate: 2,
-    });
-  });
-
-  it('clears throttling when useThrottling=false', async () => {
-    restoreActualEmulation();
-    await GatherRunner.setupPassNetwork({
-      driver,
-      settings: {
-        formFactor: 'mobile',
-        screenEmulation: constants.screenEmulationMetrics.mobile,
-        throttlingMethod: 'devtools',
-        throttling: {
-          requestLatencyMs: 100,
-          downloadThroughputKbps: 8,
-          uploadThroughputKbps: 8,
-          cpuSlowdownMultiplier: 2,
-        },
-      },
-      passConfig: {
-        useThrottling: false,
-        gatherers: [],
-      },
-    });
-
-    expect(connectionStub.sendCommand.findInvocation('Network.emulateNetworkConditions')).toEqual({
-      latency: 0, downloadThroughput: 0, uploadThroughput: 0, offline: false,
-    });
-    expect(connectionStub.sendCommand.findInvocation('Emulation.setCPUThrottlingRate')).toEqual({
-      rate: 1,
-    });
-  });
-
-  it('tells the driver to block given URL patterns when blockedUrlPatterns is given', async () => {
-    await GatherRunner.setupPassNetwork({
-      driver,
-      settings: {
-        blockedUrlPatterns: ['http://*.evil.com', '.jpg', '.woff2'],
-      },
-      passConfig: {
-        blockedUrlPatterns: ['*.jpeg'],
-        gatherers: [],
-      },
-    });
-
-    const blockedUrlsResult = connectionStub.sendCommand.findInvocation('Network.setBlockedURLs');
-    blockedUrlsResult.urls.sort();
-    expect(blockedUrlsResult)
-      .toEqual({urls: ['*.jpeg', '.jpg', '.woff2', 'http://*.evil.com']});
-  });
-
-  it('does not throw when blockedUrlPatterns is not given', async () => {
-    await GatherRunner.setupPassNetwork({
-      driver,
-      settings: {},
-      passConfig: {gatherers: []},
-    });
-
-    expect(connectionStub.sendCommand.findInvocation('Network.setBlockedURLs'))
-      .toEqual({urls: []});
-  });
-
-  it('tells the driver to set additional http when extraHeaders flag is given', async () => {
-    const extraHeaders = {
-      'Cookie': 'monster',
-      'x-men': 'wolverine',
-    };
-
-    await GatherRunner.setupPassNetwork({
-      driver,
-      settings: {
-        extraHeaders,
-      },
-      passConfig: {gatherers: []},
-    });
-
-    expect(connectionStub.sendCommand.findInvocation('Network.setExtraHTTPHeaders'))
-      .toEqual({headers: extraHeaders});
-  });
-
   it('tells the driver to begin tracing', async () => {
     let calledTrace = false;
     const driver = {
diff --git a/lighthouse-core/test/gather/gatherers/js-usage-test.js b/lighthouse-core/test/gather/gatherers/js-usage-test.js
index 5a6ec83cd..c2a7af6d5 100644
--- a/lighthouse-core/test/gather/gatherers/js-usage-test.js
+++ b/lighthouse-core/test/gather/gatherers/js-usage-test.js
@@ -13,6 +13,7 @@ const Driver = require('../../../gather/driver.js');
 const Connection = require('../../../gather/connections/connection.js');
 const JsUsage = require('../../../gather/gatherers/js-usage.js');
 const {createMockSendCommandFn, createMockOnFn} = require('../mock-commands.js');
+const {flushAllTimersAndMicrotasks} = require('../../test-utils.js');
 
 describe('JsUsage gatherer', () => {
   /**
@@ -45,10 +46,20 @@ describe('JsUsage gatherer', () => {
     const driver = new Driver(connectionStub);
 
     const gatherer = new JsUsage();
-    await gatherer.beforePass({driver});
+    await gatherer.startInstrumentation({driver});
+    await gatherer.startSensitiveInstrumentation({driver});
+
     // Needed for protocol events to emit.
-    jest.advanceTimersByTime(1);
-    return gatherer.afterPass({driver});
+    await flushAllTimersAndMicrotasks(1);
+
+    expect(gatherer._scriptParsedEvents).toEqual(scriptParsedEvents);
+
+    await gatherer.stopSensitiveInstrumentation({driver});
+    await gatherer.stopInstrumentation({driver});
+
+    expect(gatherer._scriptUsages).toEqual(coverage);
+
+    return gatherer.getArtifact();
   }
 
   it('combines coverage data by url', async () => {
diff --git a/lighthouse-core/test/test-utils.js b/lighthouse-core/test/test-utils.js
index c31186e58..2620a1f6c 100644
--- a/lighthouse-core/test/test-utils.js
+++ b/lighthouse-core/test/test-utils.js
@@ -241,6 +241,10 @@ function makeMocksForGatherRunner() {
     throttle: jest.fn(),
     clearThrottling: jest.fn(),
   }));
+  jest.mock('../gather/driver/prepare.js', () => ({
+    prepareTargetForNavigationMode: jest.fn(),
+    prepareTargetForIndividualNavigation: jest.fn().mockResolvedValue({warnings: []}),
+  }));
   jest.mock('../gather/driver/storage.js', () => ({
     clearDataForOrigin: jest.fn(),
     cleanBrowserCaches: jest.fn(),
diff --git a/third-party/chromium-webtests/webtests/http/tests/devtools/lighthouse/lighthouse-successful-run-expected.txt b/third-party/chromium-webtests/webtests/http/tests/devtools/lighthouse/lighthouse-successful-run-expected.txt
index ad9396418..9b28e893e 100644
--- a/third-party/chromium-webtests/webtests/http/tests/devtools/lighthouse/lighthouse-successful-run-expected.txt
+++ b/third-party/chromium-webtests/webtests/http/tests/devtools/lighthouse/lighthouse-successful-run-expected.txt
@@ -25,8 +25,8 @@ Benchmarking machine
 Initializing…
 Running defaultPass pass
 Resetting state with about:blank
-Setting up network for the pass trace
 Cleaning browser cache
+Preparing network conditions
 Running beforePass methods
 Gathering setup: CSSUsage
 Gathering setup: JsUsage
@@ -124,7 +124,7 @@ Get webapp manifest
 Collect stacks
 Running offlinePass pass
 Resetting state with about:blank
-Setting up network for the pass trace
+Preparing network conditions
 Running beforePass methods
 Gathering setup: ServiceWorker
 Beginning devtoolsLog and trace
@@ -136,7 +136,7 @@ Running afterPass methods
 Gathering: ServiceWorker
 Running redirectPass pass
 Resetting state with about:blank
-Setting up network for the pass trace
+Preparing network conditions
 Running beforePass methods
 Gathering setup: HTTPRedirect
 Beginning devtoolsLog and trace