-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathserializeAttributes.spec.ts
More file actions
575 lines (495 loc) · 25.5 KB
/
serializeAttributes.spec.ts
File metadata and controls
575 lines (495 loc) · 25.5 KB
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
import { isSafari } from '@datadog/browser-core'
import { registerCleanupTask } from '@datadog/browser-core/test'
import {
CENSORED_IMG_MARK,
CENSORED_STRING_MARK,
NodePrivacyLevel,
PRIVACY_ATTR_NAME,
shouldMaskNode,
STABLE_ATTRIBUTES,
} from '@datadog/browser-rum-core'
import { appendElement } from '@datadog/browser-rum-core/test'
import { createSerializationTransactionForTesting } from '../test/serialization.specHelper'
import type { ScrollPositions } from '../elementsScrollPositions'
import { getCssRulesString, serializeDOMAttributes, serializeVirtualAttributes } from './serializeAttributes'
import { SerializationKind, type SerializationTransaction } from './serializationTransaction'
import type { VirtualAttributes } from './serialization.types'
import type { SerializationMetric, SerializationStats } from './serializationStats'
import { createSerializationStats } from './serializationStats'
const CSS_FILE_URL = '/base/packages/rum/test/toto.css'
const PRIVACY_LEVELS = Object.keys({
[NodePrivacyLevel.ALLOW]: true,
[NodePrivacyLevel.HIDDEN]: true,
[NodePrivacyLevel.IGNORE]: true,
[NodePrivacyLevel.MASK]: true,
[NodePrivacyLevel.MASK_UNLESS_ALLOWLISTED]: true,
[NodePrivacyLevel.MASK_USER_INPUT]: true,
} satisfies Record<NodePrivacyLevel, true>) as NodePrivacyLevel[]
describe('serializeDOMAttributes', () => {
let transaction: SerializationTransaction
beforeEach(() => {
transaction = createSerializationTransactionForTesting()
})
it('serializes attribute values', () => {
interface TestCase {
// A snippet of HTML containing an attribute we should serialize.
// For example: `<div attr="foo">`
html: string
// By default, the attribute that should be serialized is determined automatically,
// but you can override the default behavior by specifying an attribute manually.
attrName?: string
// By default, the attribute value that should be serialized is determined automatically,
// but you can override the default behavior by specifying a value manually.
attrValue?: string
// The serialization behavior we expect. There are several options:
// - 'always-unmasked': We expect the value to be unmasked regardless of privacy
// level. For HIDDEN, we expect the value not to be serialized.
// - 'maskable': We expect the value to be masked or unmasked, depending on the
// privacy level. For HIDDEN, we expect the value not to be serialized.
// - 'maskable-form': Behaves like 'maskable' for truthy attribute values and like
// 'always-unmasked' for falsy ones. Used for most form elements.
// - 'maskable-form-boolean': The attribute as boolean true or false, depending on
// whether it's present, when unmasked. If it's masked, the attribute is not
// serialized at all. Used for boolean form element attributes like `<option selected>`.
// - 'maskable-image': Like 'maskable', except that we expect the masked
// representation to be a data URL image.
// - 'maskable-option-selected': Like 'maskable-boolean', in that when unmasked the
// representation is a boolean value. However, when the value is masked, instead of
// not being serialized, its underlying string value is used. The effect is a weird
// hybrid of 'always-unmasked' and 'maskable-boolean'.
// TODO: Reduce the complexity here by aligning 'maskable-form',
// 'maskable-form-boolean', and 'maskable-option-selected'.
expectedBehavior:
| 'always-unmasked'
| 'maskable'
| 'maskable-form'
| 'maskable-form-boolean'
| 'maskable-image'
| 'maskable-option-selected'
// How to treat the IGNORE privacy level. The default is 'unmasked'.
// TODO: Eliminate this inconsistency by always masking for IGNORE.
ignoreBehavior?: 'masked' | 'unmasked'
// How to treat the MASK_UNLESS_ALLOWLISTED privacy level. The default is 'default'.
// TODO: Eliminate this inconsistency by fixing <input type="color">, which behaves
// differently than any other kind of input.
maskUnlessAllowlistedBehavior?: 'default' | 'unmasked'
}
const testCases: TestCase[] = [
// Privacy attributes should always be unmasked.
{ html: `<div ${PRIVACY_ATTR_NAME}="value">`, expectedBehavior: 'always-unmasked' },
// Stable attributes should always be unmasked.
...STABLE_ATTRIBUTES.map(
(attribute: string): TestCase => ({
html: `<div ${attribute}="value">`,
expectedBehavior: 'always-unmasked',
})
),
// Most data attributes should be maskable.
{ html: '<div data-foo="value">', expectedBehavior: 'maskable' },
{ html: '<div data-any-attribute="value">', expectedBehavior: 'maskable' },
// Data attributes with no values should always be unmasked.
{ html: '<div data-empty-attribute>', expectedBehavior: 'always-unmasked' },
// Attributes which are likely to contain human-readable text should be maskable.
{ html: '<div title="value">', expectedBehavior: 'maskable' },
{
html: '<img alt="value">',
// TODO: This is a bug! This should just be 'maskable'.
expectedBehavior: 'maskable-image',
},
{ html: '<div alt="value">', expectedBehavior: 'maskable' },
{ html: '<input type="text" placeholder="value">', expectedBehavior: 'maskable' },
{ html: '<div placeholder="value">', expectedBehavior: 'maskable' },
{ html: '<div aria-label="value">', expectedBehavior: 'maskable' },
{ html: '<input name="value">', expectedBehavior: 'maskable' },
{ html: '<div name="value">', expectedBehavior: 'maskable' },
// Element/attribute combinations which may contain user-identifying ids and tokens
// should be maskable. The same attributes should always be unmasked in other
// contexts.
{ html: '<a href="value">', expectedBehavior: 'maskable' },
{ html: '<div href="value">', expectedBehavior: 'always-unmasked' },
{ html: '<iframe srcdoc="value">', expectedBehavior: 'maskable' },
{ html: '<div srcdoc="value">', expectedBehavior: 'always-unmasked' },
{ html: '<img src="value">', expectedBehavior: 'maskable-image' },
{ html: '<img srcset="value">', expectedBehavior: 'maskable-image' },
{ html: '<source src="value">', expectedBehavior: 'maskable-image' },
{ html: '<source srcset="value">', expectedBehavior: 'maskable-image' },
{ html: '<div src="value">', expectedBehavior: 'always-unmasked' },
{ html: '<div srcset="value">', expectedBehavior: 'always-unmasked' },
// The value attributes of button-like form elements should always be unmasked.
{ html: '<input type="button" value="value">', expectedBehavior: 'always-unmasked' },
{ html: '<input type="reset" value="value">', expectedBehavior: 'always-unmasked' },
{ html: '<input type="submit" value="value">', expectedBehavior: 'always-unmasked' },
// The value attributes of other form elements should be maskable.
{ html: '<input type="checkbox" value="value">', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="checkbox" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{
html: '<input type="color" value="#e66465">',
expectedBehavior: 'maskable',
ignoreBehavior: 'masked',
// TODO: This is almost certainly a bug; it's quite odd that only <input
// type="color"> behaves this way. The intention was probably to make it behave
// like the maskable-form input elements, but the implementation was incomplete.
maskUnlessAllowlistedBehavior: 'unmasked',
},
{
html: '<input type="color" value>',
attrValue: '#000000', // This is the value returned by HTMLInputElement#value for this test case.
expectedBehavior: 'maskable',
ignoreBehavior: 'masked',
maskUnlessAllowlistedBehavior: 'unmasked',
},
{
html: '<input type="date" value="2018-06-12">',
expectedBehavior: 'maskable',
ignoreBehavior: 'masked',
},
{
html: '<input type="date" value>',
expectedBehavior: 'maskable-form',
ignoreBehavior: 'masked',
},
{
html: '<input type="datetime-local" value="2018-06-12T19:30">',
expectedBehavior: 'maskable',
ignoreBehavior: 'masked',
},
{
html: '<input type="datetime-local" value>',
expectedBehavior: 'maskable-form',
ignoreBehavior: 'masked',
},
{ html: '<input type="email" value="value">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="email" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{
html: '<input type="file" value="C:\\fakepath\\file.txt">',
// TODO: This is a bug! It happens because HTMLInputElement#value is falsy until
// the user has actually selected a file, causing us to ignore the result of
// getElementInputValue() and fall back to the DOM attribute value.
expectedBehavior: 'always-unmasked',
},
{
html: '<input type="file" value>',
expectedBehavior: 'maskable-form',
},
{ html: '<input type="hidden" value="value">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="hidden" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="image" value="value">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="image" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="month" value="2018-05">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="month" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="number" value="42">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="number" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="password" value="value">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="password" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="radio" value="value">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="radio" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="range" value="99">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{
html: '<input type="range" value>',
attrValue: '50', // This is the value returned by HTMLInputElement#value for this test case.
expectedBehavior: 'maskable',
ignoreBehavior: 'masked',
},
{ html: '<input type="search" value="value">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="search" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="tel" value="value">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="tel" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="text" value="value">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="text" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="time" value="13:30">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="time" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="url" value="value">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="url" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
{ html: '<input type="week" value="2017-W01">', expectedBehavior: 'maskable', ignoreBehavior: 'masked' },
{ html: '<input type="week" value>', expectedBehavior: 'maskable-form', ignoreBehavior: 'masked' },
// Boolean form element attributes should be maskable, but with special behavior:
// when masked, the entire attribute should not be serialized.
{
html: '<option selected>',
// TODO: This is a bug! If the <option> is masked, we don't set the value of
// 'selected' based on the property, but we still allow the DOM attribute to be
// recorded. We should fix this; this should be 'maskable-boolean'.
expectedBehavior: 'maskable-option-selected',
ignoreBehavior: 'masked',
},
{
html: '<input type="checkbox" checked>',
expectedBehavior: 'maskable-form-boolean',
ignoreBehavior: 'masked',
},
{
html: '<input type="radio" checked>',
expectedBehavior: 'maskable-form-boolean',
ignoreBehavior: 'masked',
},
]
for (const testCase of testCases) {
const element = appendElement(testCase.html)
const attribute = getAttributeToSerialize(element, testCase.attrName)
// Remove the element from the document so that 'maskable-image' elements all have a zero
// size, giving all such attributes the same expected value.
element.remove()
for (const privacyLevel of PRIVACY_LEVELS) {
const attributes = serializeDOMAttributes(element, privacyLevel, transaction)
const actual = attributes[attribute.name] as boolean | string | undefined
const expected = expectedValueForPrivacyLevel(testCase, element, attribute, privacyLevel)
expect(actual).withContext(`${testCase.html} for ${privacyLevel}`).toEqual(expected)
}
}
function getAttributeToSerialize(
element: HTMLElement,
attrName: string | undefined
): { name: string; value: string | undefined } {
if (attrName) {
// The attribute to serialize was explicitly specified.
return { name: attrName, value: element.getAttribute(attrName) || undefined }
}
// Infer the attribute to serialize. We use the first attribute that isn't 'type'.
for (let i = 0; i < element.attributes.length; i++) {
const attr = element.attributes.item(i)
if (attr && attr.name !== 'type') {
return attr
}
}
throw new Error("Couldn't determine test attribute")
}
function expectedValueForPrivacyLevel(
testCase: TestCase,
element: Element,
attribute: { name: string; value: string | undefined },
privacyLevel: NodePrivacyLevel
): boolean | string | undefined {
let unmaskedValue: boolean | string | undefined = testCase.attrValue ?? attribute.value
if (
testCase.expectedBehavior === 'maskable-form-boolean' ||
testCase.expectedBehavior === 'maskable-option-selected'
) {
unmaskedValue = attribute.value === ''
}
let maskedValue: boolean | string | undefined
if (testCase.expectedBehavior === 'maskable-form') {
maskedValue = !unmaskedValue ? unmaskedValue : CENSORED_STRING_MARK
} else if (testCase.expectedBehavior === 'maskable-form-boolean') {
maskedValue = undefined
} else if (testCase.expectedBehavior === 'maskable-image') {
maskedValue = CENSORED_IMG_MARK
} else if (testCase.expectedBehavior === 'maskable-option-selected') {
maskedValue = attribute.value
} else {
maskedValue = CENSORED_STRING_MARK
}
if (testCase.expectedBehavior === 'always-unmasked') {
return privacyLevel === NodePrivacyLevel.HIDDEN ? undefined : unmaskedValue
}
switch (privacyLevel) {
case NodePrivacyLevel.ALLOW:
return unmaskedValue
case NodePrivacyLevel.HIDDEN:
return undefined
case NodePrivacyLevel.IGNORE:
return testCase.ignoreBehavior === 'masked' ? maskedValue : unmaskedValue
case NodePrivacyLevel.MASK:
return maskedValue
case NodePrivacyLevel.MASK_UNLESS_ALLOWLISTED:
if (testCase.maskUnlessAllowlistedBehavior === 'unmasked') {
return unmaskedValue
}
return maskedValue
case NodePrivacyLevel.MASK_USER_INPUT:
return ['checked', 'selected', 'value'].includes(attribute.name) &&
shouldMaskNode(element, NodePrivacyLevel.MASK_USER_INPUT)
? maskedValue
: unmaskedValue
default:
privacyLevel satisfies never
return undefined
}
}
})
it('normalizes tag names', () => {
// Create an <option> element in the SVG namespace. This makes it an XML element;
// among other things, this results in a lowercase Element#tagName.
const element = document.createElementNS('http://www.w3.org/2000/svg', 'option')
expect(element.tagName).toBe('option')
// Check that serializeDOMAttributes() still executes <option>-specific serialization
// behavior; it shouldn't behave differently because Element#tagName is lowercase.
;(element as any).selected = true
const attributes = serializeDOMAttributes(element, NodePrivacyLevel.ALLOW, transaction)
expect(attributes['selected']).toBe(true)
})
})
describe('serializeVirtualAttributes', () => {
let stats: SerializationStats
let transaction: SerializationTransaction
beforeEach(() => {
stats = createSerializationStats()
transaction = createSerializationTransactionForTesting({ stats })
})
function expectVirtualAttributes(
element: Element,
expectedWhenNotHidden: VirtualAttributes,
after?: (privacyLevel: NodePrivacyLevel) => void
): void {
for (const privacyLevel of PRIVACY_LEVELS) {
const actual = serializeVirtualAttributes(element, privacyLevel, transaction)
const expected = privacyLevel === NodePrivacyLevel.HIDDEN ? {} : expectedWhenNotHidden
expect(actual).withContext(`${element.tagName} ${privacyLevel}`).toEqual(expected)
after?.(privacyLevel)
}
}
describe('when serializing CSS text', () => {
const cssText = 'div { background-color: green; top: 5px; }'
const cssTextStats: SerializationMetric = { count: 1, max: 42, sum: 42 }
const emptyStats: SerializationMetric = { count: 0, max: 0, sum: 0 }
function checkStats(privacyLevel: NodePrivacyLevel): void {
expect(stats.cssText).toEqual(privacyLevel === NodePrivacyLevel.HIDDEN ? emptyStats : cssTextStats)
stats.cssText = { ...emptyStats }
}
it('handles link element stylesheets', async () => {
const cssBlob = new Blob([cssText], { type: 'text/css' })
const cssUrl = URL.createObjectURL(cssBlob)
const link = document.createElement('link')
registerCleanupTask(() => {
link.parentNode?.removeChild(link)
})
link.setAttribute('rel', 'stylesheet')
link.setAttribute('href', cssUrl)
const linkLoaded = new Promise((resolve) => link.addEventListener('load', resolve))
document.body.appendChild(link)
await linkLoaded
if (isSafari() && !Array.from(document.styleSheets).find((sheet) => sheet.href === link.href)) {
// Safari 12 fails to load the stylesheet from the blob URL.
return
}
expectVirtualAttributes(link, { _cssText: cssText }, checkStats)
})
it('handles style element stylesheets', () => {
const style = appendElement(`<style>${cssText}</style>`)
expectVirtualAttributes(style, { _cssText: cssText }, checkStats)
})
})
it('serializes media element playback state', () => {
for (const tag of ['audio', 'video']) {
const media = appendElement(`<${tag}>`)
let isPaused: boolean
Object.defineProperty(media, 'paused', { get: () => isPaused })
isPaused = true
expectVirtualAttributes(media, { rr_mediaState: 'paused' })
isPaused = false
expectVirtualAttributes(media, { rr_mediaState: 'played' })
}
})
describe('when serializing scroll state', () => {
it('reads from the DOM for the initial full snapshot', () => {
transaction.kind = SerializationKind.INITIAL_FULL_SNAPSHOT
const div = appendElement('<div>')
const expected: ScrollPositions = {
scrollLeft: 0,
scrollTop: 0,
}
Object.defineProperty(div, 'scrollLeft', { get: () => expected.scrollLeft })
Object.defineProperty(div, 'scrollTop', { get: () => expected.scrollTop })
// For the initial full snapshot, we should read these values from the DOM. Store
// unexpected values in ElementScrollPositions so that we can detect if they're
// mistakenly used. Note that serializeVirtualAttributes() will write updated values
// into ElementScrollPositions, so we need to reset it for each expectation.
const poisonedScrollPositions = { scrollLeft: 9999, scrollTop: 9999 }
transaction.scope.elementsScrollPositions.set(div, poisonedScrollPositions)
const resetPoisonedScrollPositions = (privacyLevel: NodePrivacyLevel) => {
const expectedStoredPositionsToChange =
privacyLevel !== NodePrivacyLevel.HIDDEN && (expected.scrollLeft || expected.scrollTop)
const expectedStoredPositions = expectedStoredPositionsToChange ? expected : poisonedScrollPositions
expect(transaction.scope.elementsScrollPositions.get(div)).toEqual(expectedStoredPositions)
transaction.scope.elementsScrollPositions.set(div, poisonedScrollPositions)
}
expected.scrollLeft = 1
expected.scrollTop = 2
expectVirtualAttributes(div, { rr_scrollLeft: 1, rr_scrollTop: 2 }, resetPoisonedScrollPositions)
expected.scrollLeft = 0
expected.scrollTop = 3
expectVirtualAttributes(div, { rr_scrollTop: 3 }, resetPoisonedScrollPositions)
expected.scrollLeft = 4
expected.scrollTop = 0
expectVirtualAttributes(div, { rr_scrollLeft: 4 }, resetPoisonedScrollPositions)
expected.scrollLeft = 0
expected.scrollTop = 0
expectVirtualAttributes(div, {}, resetPoisonedScrollPositions)
})
it('reads from ElementsScrollPositions for subsequent full snapshots', () => {
transaction.kind = SerializationKind.SUBSEQUENT_FULL_SNAPSHOT
const div = appendElement('<div>')
// For subsequent full snapshots, we should read these values from
// ElementScrollPositions. Store unexpected values in the DOM so that we can detect
// if they're mistakenly used.
Object.defineProperty(div, 'scrollLeft', { value: 9999 })
Object.defineProperty(div, 'scrollTop', { value: 9999 })
const expected: ScrollPositions = {
scrollLeft: 0,
scrollTop: 0,
}
transaction.scope.elementsScrollPositions.set(div, expected)
const checkElementScrollPositions = () => {
expect(transaction.scope.elementsScrollPositions.get(div)).toEqual(expected)
}
expected.scrollLeft = 1
expected.scrollTop = 2
expectVirtualAttributes(div, { rr_scrollLeft: 1, rr_scrollTop: 2 }, checkElementScrollPositions)
expected.scrollLeft = 0
expected.scrollTop = 3
expectVirtualAttributes(div, { rr_scrollTop: 3 }, checkElementScrollPositions)
expected.scrollLeft = 4
expected.scrollTop = 0
expectVirtualAttributes(div, { rr_scrollLeft: 4 }, checkElementScrollPositions)
expected.scrollLeft = 0
expected.scrollTop = 0
expectVirtualAttributes(div, {}, checkElementScrollPositions)
})
})
it('normalizes tag names', () => {
// Create an <audio> element in the SVG namespace. This makes it an XML element;
// among other things, this results in a lowercase Element#tagName.
const element = document.createElementNS('http://www.w3.org/2000/svg', 'audio')
expect(element.tagName).toBe('audio')
// Check that serializeVirtualAttributes() still executes <audio>-specific serialization
// behavior; it shouldn't behave differently because Element#tagName is lowercase.
;(element as any).paused = true
const attributes = serializeVirtualAttributes(element, NodePrivacyLevel.ALLOW, transaction)
expect(attributes.rr_mediaState).toBe('paused')
})
})
describe('getCssRulesString', () => {
let styleNode: HTMLStyleElement
beforeEach(() => {
styleNode = document.createElement('style')
document.body.appendChild(styleNode)
registerCleanupTask(() => {
document.body.removeChild(styleNode)
})
})
it('returns the CSS rules as a string', () => {
styleNode.sheet!.insertRule('body { color: red; }')
expect(getCssRulesString(styleNode.sheet)).toBe('body { color: red; }')
})
it('properly escapes CSS rules selectors containing a colon', () => {
styleNode.sheet!.insertRule('[foo\\:bar] { display: none; }')
expect(getCssRulesString(styleNode.sheet)).toBe('[foo\\:bar] { display: none; }')
})
it('inlines imported external stylesheets', () => {
styleNode.sheet!.insertRule(`@import url("${CSS_FILE_URL}");`)
// Simulates an accessible external stylesheet
spyOnProperty(styleNode.sheet!.cssRules[0] as CSSImportRule, 'styleSheet').and.returnValue({
cssRules: [{ cssText: 'p { margin: 0; }' } as CSSRule] as unknown as CSSRuleList,
} as CSSStyleSheet)
expect(getCssRulesString(styleNode.sheet)).toBe('p { margin: 0; }')
})
it('does not skip the @import rules if the external stylesheet is inaccessible', () => {
styleNode.sheet!.insertRule(`@import url("${CSS_FILE_URL}");`)
// Simulates an inaccessible external stylesheet
spyOnProperty(styleNode.sheet!.cssRules[0] as CSSImportRule, 'styleSheet').and.returnValue({
get cssRules(): CSSRuleList {
throw new Error('Cannot access rules')
},
} as CSSStyleSheet)
expect(getCssRulesString(styleNode.sheet)).toBe(`@import url("${CSS_FILE_URL}");`)
})
})