| // Copyright 2020 The Chromium Authors | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| /* | |
| * This file is automatically loaded and run by Karma because it automatically | |
| * loads and injects all *.js files it finds. | |
| */ | |
| import '../third_party/chromium/ahem/ahem.js'; | |
| import {afterEach, before, beforeEach} from 'mocha'; | |
| import sinon from 'sinon'; | |
| import * as Common from '../core/common/common.js'; | |
| import * as Host from '../core/host/host.js'; | |
| import * as Trace from '../models/trace/trace.js'; | |
| import * as TraceSourceMapsResolver from '../models/trace_source_maps_resolver/trace_source_maps_resolver.js'; | |
| import * as UI from '../ui/legacy/legacy.js'; | |
| import * as ThemeSupport from '../ui/legacy/theme_support/theme_support.js'; | |
| import {cleanTestDOM, setupTestDOM} from './DOMHooks.js'; | |
| import {createFakeSetting, resetHostConfig} from './EnvironmentHelpers.js'; | |
| import {hasPendingTestTeardowns, runTestTeardowns, setRootTeardownRunnerRegistered} from './TestTeardown.js'; | |
| import {TraceLoader} from './TraceLoader.js'; | |
| import { | |
| checkForPendingActivity, | |
| flushPendingActivity, | |
| startTrackingAsyncActivity, | |
| stopTrackingAsyncActivity, | |
| } from './TrackAsyncOperations.js'; | |
| import {checkForUnexpectedConsoleLogs, startTrackingConsoleLogs, stopTrackingConsoleLogs} from './TrackConsoleLogs.js'; | |
| /** | |
| * `hasOnly` is not part of Mocha's public API. | |
| */ | |
| interface SuiteWithHasOnly extends Mocha.Suite { | |
| hasOnly?: () => boolean; | |
| } | |
| interface TestWithExclusiveTests extends Mocha.Test { | |
| // Custom extension: attached in beforeEach to signal to Karma that exclusive tests (e.g. it.only) are being run. | |
| hasExclusiveTests?: boolean; | |
| } | |
| async function setupTestFont() { | |
| document.documentElement.classList.add('platform-screenshot-test'); | |
| Host.Platform.setFontFamilyForTests('ahem'); | |
| } | |
| before(async function() { | |
| // All setup function should manage their own timeout | |
| this.timeout(0); | |
| setRootTeardownRunnerRegistered(); | |
| await setupTestFont(); | |
| // There is no way to provide after each file run via a test set up file. | |
| // What we do instead is add and after all in all global test suits | |
| // This is as close as we can get to after each file. | |
| this.test?.parent?.suites.forEach(function(suite) { | |
| suite.afterAll(function() { | |
| TraceLoader.resetCache(); | |
| }); | |
| }); | |
| }); | |
| beforeEach(async function(this: Mocha.Context) { | |
| const currentTest: TestWithExclusiveTests|undefined = this.currentTest; | |
| if (currentTest) { | |
| const parent: SuiteWithHasOnly|undefined = currentTest.parent; | |
| currentTest.hasExclusiveTests = parent?.hasOnly?.(); | |
| } | |
| // Clear out any Sinon stubs or spies between individual tests. | |
| sinon.restore(); | |
| stopTrackingAsyncActivity(); | |
| stopTrackingConsoleLogs(); | |
| if (hasPendingTestTeardowns()) { | |
| const title = this.currentTest?.fullTitle(); | |
| console.error(`Leftover test teardowns before "${ | |
| title}"; registerTestTeardown() must only be called while a test is running`); | |
| try { | |
| await runTestTeardowns(); | |
| } catch (err) { | |
| console.error(`Error draining leftover test teardowns before "${title}":`, err); | |
| } | |
| } | |
| resetHostConfig(); | |
| await setupTestDOM(); | |
| // Ensure that no trace data leaks between tests when testing the trace engine. | |
| for (const handler of Object.values(Trace.Handlers.ModelHandlers)) { | |
| handler.reset(); | |
| } | |
| Trace.Helpers.SyntheticEvents.SyntheticEventsManager.reset(); | |
| TraceSourceMapsResolver.SourceMapsResolver.clearResolvedNodeNames(); | |
| // Don't retain host binding listeners across tests. Set this up before initializing ThemeSupport as | |
| // ThemeSupport adds a host binding listener. | |
| Host.InspectorFrontendHost.InspectorFrontendHostInstance.events = new Common.ObjectWrapper.ObjectWrapper(); | |
| // Some unit tests exercise code that assumes a ThemeSupport instance is available. | |
| // Run this in a beforeEach in case an individual test overrides it. | |
| const setting = createFakeSetting('ui-theme', 'default'); | |
| ThemeSupport.ThemeSupport.instance({forceNew: true, setting}); | |
| startTrackingAsyncActivity(); | |
| startTrackingConsoleLogs(); | |
| }); | |
| afterEach(async function() { | |
| const title = this.currentTest?.fullTitle(); | |
| // Run every cleanup step even if an earlier one throws, so that a failure in | |
| // one step can't leave fake timers, Sinon stubs or tracking stubs installed. | |
| const errors: unknown[] = []; | |
| const run = async(step: () => unknown): Promise<void> => { | |
| try { | |
| await step(); | |
| } catch (err) { | |
| errors.push(err); | |
| } | |
| }; | |
| // Invariant: everything that can still render (fake timers, DOM cleanup, pending async work) | |
| // must run while the per-test environment (locale, settings, target manager, actions) is still | |
| // intact. | |
| await run(() => cleanTestDOM(title)); | |
| await run(() => sinon.clock?.runToLast()); | |
| await run(() => sinon.clock?.restore()); | |
| await run(() => flushPendingActivity(20)); | |
| await run(() => UI.Widget.Widget.flushPendingUpdatesForTesting()); | |
| await run(() => flushPendingActivity(20)); | |
| // Now that all pending renders have settled, run registered per-test teardowns (LIFO order). | |
| await run(() => runTestTeardowns()); | |
| // Only check for leaked async operations when the test completed normally. | |
| // Failed or timed-out tests abort mid-execution while async work is still in flight. | |
| if (this.currentTest?.state === 'passed') { | |
| await run(() => checkForPendingActivity(title)); | |
| } | |
| // Restore Sinon (including fake timers) before the tracking stubs, matching | |
| // the order in the root beforeEach. | |
| await run(() => sinon.restore()); | |
| await run(() => stopTrackingAsyncActivity()); | |
| if (this.currentTest?.state === 'passed') { | |
| await run(() => checkForUnexpectedConsoleLogs(title)); | |
| } | |
| await run(() => stopTrackingConsoleLogs()); | |
| if (errors.length === 0) { | |
| return; | |
| } | |
| for (const err of errors.slice(1)) { | |
| console.error(`Additional afterEach cleanup error in "${title}":`, err); | |
| } | |
| if (this.currentTest && this.test) { | |
| // Fail the test itself via Hook.error() instead of failing the root afterEach hook, | |
| // which would cause Mocha to abort the root suite and skip all remaining tests. | |
| (this.test as Mocha.Hook).error(errors[0]); | |
| return; | |
| } | |
| throw errors[0]; | |
| }); |