/
TestBrowser.tsx
364 lines (281 loc) · 13.9 KB
/
TestBrowser.tsx
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { AnyFunction, ClassUnion, Mixin } from "../../class/Mixin.js"
import { ExecutionContext } from "../../context/ExecutionContext.js"
import { ExecutionContextAttachableBrowser, ExecutionContextBrowser } from "../../context/ExecutionContextBrowser.js"
import { TextJSX } from "../../jsx/TextJSX.js"
import { isNodejs, prototypeValue, typeOf, wantArray } from "../../util/Helpers.js"
import { awaitDomInteractive, elementFromPoint } from "../../util_browser/Dom.js"
import { isHTMLLinkElement, isHTMLScriptElement } from "../../util_browser/Typeguards.js"
import { Launcher } from "../launcher/Launcher.js"
import { ExitCodes } from "../launcher/Types.js"
import { ConsoleXmlRenderer } from "../reporter/ConsoleXmlRenderer.js"
import { PointerMovePrecision } from "../simulate/SimulatorMouse.js"
import { ActionTarget, Simulator } from "../simulate/Types.js"
import { UserAgentOnPage } from "../simulate/UserAgent.js"
import { MouseCursorVisualizer } from "../ui/MouseCursorVisualizer.js"
import { AssertionElement } from "./assertion/AssertionElement.js"
import { AssertionObservable } from "./assertion/AssertionObservable.js"
import { TextSelectionHelpers } from "./browser/TextSelectionHelpers.js"
import { TestLauncherChild } from "./port/TestLauncherChild.js"
import { createTestSectionConstructors, Test } from "./Test.js"
import { normalizePreloadDescriptor, TestDescriptorBrowser } from "./TestDescriptorBrowser.js"
import { Assertion, Exception, SubTestCheckInfo } from "./TestResult.js"
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
/**
* Test class for code running in the browser environment.
*
* Please refer to the [[TestDescriptorBrowser]] documentation for the list of available config options.
*/
export class TestBrowser extends Mixin(
[
UserAgentOnPage,
AssertionObservable,
AssertionElement,
TextSelectionHelpers,
ExecutionContextAttachableBrowser,
Test
],
(base : ClassUnion<
typeof UserAgentOnPage,
typeof AssertionObservable,
typeof AssertionElement,
typeof TextSelectionHelpers,
typeof ExecutionContextAttachableBrowser,
typeof Test
>) =>
class TestBrowser extends base {
// allow the browser test initialize w/o exception even in Node.js environment
// (we'll issue a meaningful error in this case later)
window : Window = typeof window !== 'undefined' ? window : undefined
@prototypeValue(TestDescriptorBrowser)
testDescriptorClass : typeof TestDescriptorBrowser
descriptor : TestDescriptorBrowser
// @prototypeValue(ExecutionContextBrowser)
// executionContextClass : typeof ExecutionContext
connector : TestLauncherChild & Simulator
mouseCursorVisualizer : MouseCursorVisualizer = MouseCursorVisualizer.new()
addListenerToObservable (observable : unknown, event : string, listener : AnyFunction) {
// @ts-ignore
observable.addEventListener(event, listener)
}
removeListenerFromObservable (observable : unknown, event : string, listener : AnyFunction) {
// @ts-ignore
observable.removeEventListener(event, listener)
}
resolveObservable (source : ActionTarget) : unknown {
return this.resolveActionTarget(source)
}
get onAmbiguousQuery () : 'use_first' | 'warn' | 'throw' {
return this.descriptor.onAmbiguousQuery
}
get mouseMovePrecision () : PointerMovePrecision {
return this.descriptor.mouseMovePrecision
}
// @ts-expect-error
get simulator () : Simulator {
return this.connector
}
set simulator (value : Simulator) {
}
async setupPreloads () {
await awaitDomInteractive()
// TODO clean this up once the support for in-test config is implemented
// there's now pre-normalization step in the "flatten" method,
// which converts all `PreloadDescriptor`s to `PreloadDescriptorNormalized`
// and "absolutize" their `url`s, so it seems these conversions are not needed
// even though they are not harmful (since every `PreloadDescriptorNormalized`
// is also a regular `PreloadDescriptor`)
const preloads = wantArray(this.descriptor.preload || [])
.concat(this.descriptor.preloadRel || [])
.concat(this.descriptor.alsoPreload || [])
.flat(2000)
.filter(el => Boolean(el))
.map(normalizePreloadDescriptor)
const doc = this.window.document
const waitFor : Promise<Event | undefined>[] = []
for (const preload of preloads) {
if (preload.type === 'js') {
const el = doc.createElement('script')
// @ts-ignore
el.PRELOAD = true
el.type = preload.isEcmaModule ? 'module' : 'text/javascript'
preload.isEcmaModule && el.setAttribute("crossorigin", "anonymous")
if ('url' in preload) {
// TODO clean this up, see note above
// el.src = new URL(preload.url, this.descriptor.urlAbs).href
el.src = preload.url
waitFor.push(new Promise((resolve, reject) => {
el.addEventListener('load', () => resolve(undefined))
el.addEventListener('error', resolve)
}))
}
else
el.text = preload.content
doc.head.appendChild(el)
}
else {
if ('url' in preload) {
const el = doc.createElement('link')
// @ts-ignore
el.PRELOAD = true
el.type = 'text/css'
el.rel = 'stylesheet'
// TODO clean this up, see note above
// el.href = new URL(preload.url, this.descriptor.urlAbs).href
el.href = preload.url
waitFor.push(new Promise((resolve, reject) => {
el.addEventListener('load', () => resolve(undefined))
el.addEventListener('error', resolve)
}))
doc.head.appendChild(el)
}
else {
const el = doc.createElement('style')
el.setAttribute("type", 'text/css')
el.appendChild(document.createTextNode(preload.content))
doc.head.appendChild(el)
}
}
}
const results = await Promise.all(waitFor)
for (const result of results) {
if (result) {
const target = result.target
const url = target
? isHTMLScriptElement(target)
? target.src
: isHTMLLinkElement(target)
? target.href
: undefined
: undefined
this.addResult(Assertion.new({
name : 'Resource preloading failure',
passed : false,
annotation : url
? <div>
Preloading of the `{ url }` has failed
</div>
: <div>
Preloading of the resource has failed.
</div>
}))
}
}
}
override async setupExecutionContext () {
await super.setupExecutionContext()
if (this.descriptor.failOnResourceLoadError)
this.onResourceLoadFailureHook.on((me : TestBrowser, event : Event) => {
// ignore the loading errors from the elements, that were created by the preload mechanism -
// it has its own error reporting
// @ts-ignore
if (event.target.PRELOAD) return
const target = event.target
const url = target
? isHTMLScriptElement(target)
? target.src
: isHTMLLinkElement(target)
? target.href
: undefined
: undefined
this.addResult(Assertion.new({
name : 'Resource loading failure',
passed : false,
// TODO, should probably include serialized element to the annotation
annotation : url
? <div>
Loading of the `{ url }` has failed
</div>
: <div>
Loading of the resource has failed.
</div>
}))
})
}
override async setupRootTest () {
const superSetup = super.setupRootTest()
const mouseCursorVisStart = this.mouseCursorVisualizer.start()
const doc = this.window.document
if (this.descriptor.expandBody) {
const html = doc.documentElement
const body = doc.body
body.style.width = html.style.width = '100%'
body.style.height = html.style.height = '100%'
body.style.margin = body.style.padding = '0'
}
let mousePositionRestore = Promise.resolve()
if (this.dashboardLaunchInfo) {
// @ts-expect-error
this.simulator.offset = this.dashboardLaunchInfo.offset
mousePositionRestore = await this.simulator.simulateMouseMove([ 0, 0 ], { mouseMovePrecision : { kind : 'last_only', precision : 1 } })
}
// this will await until the `super` method installs the ExecutionContext hooks
await superSetup
await Promise.all([ mouseCursorVisStart, mousePositionRestore, this.setupPreloads() ])
}
async launch (checkInfo : SubTestCheckInfo = undefined) {
if (!this.parentNode && this.window.document.compatMode === 'BackCompat') {
this.addResult(Exception.new({ exception : new Error('Test page is opened in the quirks mode') }))
return
}
await super.launch(checkInfo)
}
async tearDownRootTest () {
await super.tearDownRootTest()
this.mouseCursorVisualizer.stop()
}
getElementAtCursor (deep : boolean = true) : Element {
return elementFromPoint(this.window.document, ...this.simulator.currentPosition, deep).el
}
static async getExecutionContextClass () : Promise<typeof ExecutionContext> {
return ExecutionContextBrowser
}
static async getLauncherClass () : Promise<typeof Launcher> {
return (await import('../launcher/LauncherBrowser.js')).LauncherBrowser
}
// TODO refactor the whole launching infrastructure
static async launchStandalone () {
if (isNodejs()) {
const renderer = ConsoleXmlRenderer.new({
doPrint : str => process.stdout.write(str),
styles : (await import("../reporter/styling/theme_universal.js")).styles,
colorerClass : (await import('../../jsx/ColorerNodejs.js')).ColorerNodejs
})
renderer.write(
<div>
<span class="exception_icon"> ERROR </span> Browser test launched directly as Node.js script.{ '\n' }
Please use Siesta launcher instead and web url:{ '\n' }
<span class="accented"> http://web_path/to/your/test.js</span>
</div>
)
process.exitCode = ExitCodes.INCORRECT_ENVIRONMENT
} else
super.launchStandalone()
}
}
) {}
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
const api = createTestSectionConstructors(TestBrowser)
/**
* Alias for {@link TestBrowser.it | it} method.
*/
export const it = api.it
/**
* Alias for {@link TestBrowser.iit | iit} method.
*/
export const iit = api.iit
/**
* Alias for {@link TestBrowser.xit | xit} method.
*/
export const xit = api.xit
/**
* Alias for {@link TestBrowser.describe | describe} method.
*/
export const describe = api.describe
/**
* Alias for {@link TestBrowser.ddescribe | ddescribe} method.
*/
export const ddescribe = api.ddescribe
/**
* Alias for {@link TestBrowser.xdescribe | xdescribe} method.
*/
export const xdescribe = api.xdescribe