forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit-tests-helpers.js
204 lines (182 loc) · 5.78 KB
/
init-tests-helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
'use strict';
// These two imports must precede all others.
import '#polyfills';
import './setup_chai_sinon';
import {configure as configureEnzyme} from 'enzyme';
import PreactEnzyme from 'enzyme-adapter-preact-pure';
import {removeElement} from '#core/dom';
import {resetEvtListenerOptsSupportForTesting} from '#core/dom/event-helper-listen';
import {resetExperimentTogglesForTesting} from '#experiments';
import {Services} from '#service';
import {installDocService} from '#service/ampdoc-impl';
import {
installAmpdocServices,
installRuntimeServices,
} from '#service/core-services';
import {cancelTimersForTesting} from '#service/timer-impl';
import {preventAsyncErrorThrows} from './async-errors';
import {
maybeStubConsoleInfoLogWarn,
restoreConsoleError,
restoreConsoleSandbox,
restoreLogger,
setTestName,
setTestRunner,
stubLogger,
warnForConsoleError,
} from './console-logging-setup';
import * as describes from './describes';
import {flush as flushPreactEffects} from './preact';
import {TestConfig} from './test-config';
import {installYieldIt} from './yield';
import AMP_CONFIG from '../build-system/global-configs/prod-config.json' assert {type: 'json'}; // lgtm[js/syntax-error]
import {setDefaultBootstrapBaseUrlForTesting} from '../src/3p-frame';
import {activateChunkingForTesting} from '../src/chunk';
import {resetAccumulatedErrorMessagesForTesting} from '../src/error-reporting';
import {adoptWithMultidocDeps} from '../src/runtime';
let bentoOnly = true;
export function bentoOnlyMode() {
return bentoOnly;
}
export function setBentoMode(mode) {
bentoOnly = mode;
}
/** @fileoverview
* This file initializes AMP's Karma + Mocha based unit & integration tests.
* TODO(wg-infra): Do a detailed inventory and remove unnecessary steps.
*/
/**
* Initializes the global state required by all AMP unit and integration tests.
*/
export function initializeTests() {
initializeTestConstructs();
exposeKarmaConfig();
resetTestingState();
if (!bentoOnlyMode()) {
overrideAmpExtensionInstaller();
}
}
/**
* Exposes Karma's config constant for use during tests. The regular test runner
* uses `karma`, while the debugger uses `__karma__ `.
*/
function exposeKarmaConfig() {
if (parent.karma && !parent.__karma__) {
parent.__karma__ = parent.karma;
}
window.ampTestRuntimeConfig = parent.__karma__
? parent.__karma__.config.amp
: {};
}
/**
* Initializes the constructs with which all test cases are authored.
*/
function initializeTestConstructs() {
// Allow Mocha's it() to call yield and allow pending promises to resolve.
installYieldIt(it);
// Make Mocha's describe() and it() globally configurable.
describe.configure = () => new TestConfig(describe);
it.configure = () => new TestConfig(it);
// Make AMP's custom describes() globally available.
global.describes = describes;
// Set up Mocha's global setup / clean up functions.
before(overrideSkipTest);
beforeEach(setupTestcase);
afterEach(cleanupTestcase);
}
/**
* Overrides AMP.extension() so that extension installation is buffered and
* executed just when needed.
*/
function overrideAmpExtensionInstaller() {
global.AMP.extension = (name, version, installer) =>
describes.bufferExtension(`${name}:${version}`, installer);
}
/**
* Overrides skipTest() with a more robust version of `this.skip()`. See #17245.
*/
function overrideSkipTest() {
this.skipTest = function () {
if (!this._runnable.title.startsWith('"before all" hook')) {
throw new Error('skipTest() can only be called from within before()');
}
this.test.parent.pending = true; // Workaround for mochajs/mocha#2683.
this.skip();
};
}
/**
* Sets up the initial state required by individual test cases.
*/
function setupTestcase() {
resetTestingState();
setTestName(this.currentTest.fullTitle());
maybeStubConsoleInfoLogWarn();
preventAsyncErrorThrows();
warnForConsoleError();
stubLogger();
}
/**
* Resets AMP-specific state in the global window object.
*/
function resetWindowState() {
window.localStorage.clear();
window.ENABLE_LOG = false;
window.AMP_CONFIG = AMP_CONFIG;
window.AMP_DEV_MODE = false;
window.context = undefined;
window.__AMP_MODE = undefined;
window.__AMP_TEST = true;
delete window.document['__AMPDOC'];
}
/**
* Resets the window's testing state. Used at the start by initializeTests() and
* before each test case by setupTestcase().
*/
function resetTestingState() {
activateChunkingForTesting();
resetWindowState();
installDocService(window, /* isSingleDoc */ true);
const ampdoc = Services.ampdocServiceFor(window).getSingleDoc();
installRuntimeServices(window);
installAmpdocServices(ampdoc);
Services.resourcesForDoc(ampdoc).ampInitComplete();
if (!bentoOnlyMode()) {
adoptWithMultidocDeps(window);
}
configureEnzyme({adapter: new PreactEnzyme()});
}
/**
* Cleans up global state added during tests.
* @return {Promise<void>}
*/
async function cleanupTestcase() {
await flushPreactEffects();
setTestRunner(this);
restoreConsoleSandbox();
restoreAsyncErrorThrows();
restoreConsoleError();
restoreLogger();
cleanupTestPageElements();
resetWindowState();
setDefaultBootstrapBaseUrlForTesting(null);
resetAccumulatedErrorMessagesForTesting();
resetExperimentTogglesForTesting(window);
resetEvtListenerOptsSupportForTesting();
cancelTimersForTesting();
}
/**
* Cleans up any HTML elements that tests might have added to the document.
*/
function cleanupTestPageElements() {
const cleanupTagNames = ['link', 'meta', 'iframe'];
const cleanup = document.querySelectorAll(cleanupTagNames.join(','));
for (let i = 0; i < cleanup.length; i++) {
try {
const element = cleanup[i];
removeElement(element);
} catch (e) {
// This sometimes fails for unknown reasons.
console./*OK*/ log(e);
}
}
}