-
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathtakeElementScreenshots.test.ts
More file actions
515 lines (434 loc) · 22.2 KB
/
Copy pathtakeElementScreenshots.test.ts
File metadata and controls
515 lines (434 loc) · 22.2 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
import { beforeEach, describe, it, expect, vi, afterEach } from 'vitest'
import { join } from 'node:path'
import logger from '@wdio/logger'
import { takeElementScreenshot } from './takeElementScreenshots.js'
import { takeBase64BiDiScreenshot, takeWebElementScreenshot } from './screenshots.js'
import { makeCroppedBase64Image } from './images.js'
import { getBase64ScreenshotSize, waitFor, hasResizeDimensions } from '../helpers/utils.js'
import type { ElementScreenshotDataOptions } from './screenshots.interfaces.js'
const log = logger('test')
vi.mock('./screenshots.js', () => ({
takeBase64BiDiScreenshot: vi.fn().mockResolvedValue('bidi-screenshot-data'),
takeWebElementScreenshot: vi.fn().mockResolvedValue({
base64Image: 'web-element-screenshot-data',
rectangles: { x: 0, y: 0, width: 100, height: 100 },
isWebDriverElementScreenshot: false
})
}))
vi.mock('./images.js', () => ({
makeCroppedBase64Image: vi.fn().mockResolvedValue('cropped-screenshot-data')
}))
vi.mock('../clientSideScripts/scrollElementIntoView.js', () => ({
default: vi.fn()
}))
vi.mock('../clientSideScripts/scrollToPosition.js', () => ({
default: vi.fn()
}))
vi.mock('../helpers/utils.js', () => ({
getBase64ScreenshotSize: vi.fn().mockReturnValue({ width: 100, height: 100 }),
waitFor: vi.fn().mockResolvedValue(undefined),
hasResizeDimensions: vi.fn().mockReturnValue(false)
}))
vi.mock('@wdio/logger', () => import(join(process.cwd(), '__mocks__', '@wdio/logger')))
describe('takeElementScreenshot', () => {
const takeBase64BiDiScreenshotSpy = vi.mocked(takeBase64BiDiScreenshot)
const takeWebElementScreenshotSpy = vi.mocked(takeWebElementScreenshot)
const makeCroppedBase64ImageSpy = vi.mocked(makeCroppedBase64Image)
const getBase64ScreenshotSizeSpy = vi.mocked(getBase64ScreenshotSize)
const waitForSpy = vi.mocked(waitFor)
const hasResizeDimensionsSpy = vi.mocked(hasResizeDimensions)
const executeMock = vi.fn().mockResolvedValue(undefined)
const getElementRectMock = vi.fn().mockResolvedValue({ x: 10, y: 20, width: 100, height: 200 })
const browserInstance = {
execute: executeMock,
getElementRect: getElementRectMock
} as any
const baseOptions: ElementScreenshotDataOptions = {
addressBarShadowPadding: 6,
autoElementScroll: false,
deviceName: 'desktop',
devicePixelRatio: 2,
deviceRectangles: {
bottomBar: { height: 0, width: 390, x: 0, y: 800 },
homeBar: { height: 34, width: 390, x: 0, y: 780 },
leftSidePadding: { height: 0, width: 0, x: 0, y: 0 },
rightSidePadding: { height: 0, width: 0, x: 0, y: 0 },
screenSize: { height: 844, width: 390 },
statusBar: { height: 47, width: 390, x: 0, y: 0 },
statusBarAndAddressBar: { height: 47, width: 390, x: 0, y: 0 },
viewport: { height: 733, width: 390, x: 0, y: 47 }
},
element: { elementId: 'test-element' } as any,
isEmulated: false,
initialDevicePixelRatio: 2,
innerHeight: 900,
isAndroid: false,
isAndroidChromeDriverScreenshot: false,
isAndroidNativeWebScreenshot: false,
isIOS: false,
isLandscape: false,
isMobile: false,
resizeDimensions: { top: 0, right: 0, bottom: 0, left: 0 },
toolBarShadowPadding: 5
}
afterEach(() => {
vi.clearAllMocks()
})
describe('BiDi screenshots', () => {
it('should take BiDi screenshot from document when shouldUseBidi is true', async () => {
const result = await takeElementScreenshot(browserInstance, baseOptions, true)
expect(result).toEqual({
base64Image: 'bidi-screenshot-data',
isWebDriverElementScreenshot: false
})
expect(getElementRectMock).toHaveBeenCalledWith('test-element')
expect(takeBase64BiDiScreenshotSpy).toHaveBeenCalledWith({
browserInstance,
origin: 'document',
clip: { x: 10, y: 20, width: 100, height: 200 }
})
expect(takeWebElementScreenshotSpy).not.toHaveBeenCalled()
expect(makeCroppedBase64ImageSpy).not.toHaveBeenCalled()
})
//
// We intentionally rely on BiDi with origin: 'document' only. If that
// ever fails, we surface the underlying error instead of silently
// falling back to a different origin with mismatched coordinates.
it('should scroll element into view when autoElementScroll is enabled', async () => {
const optionsWithScroll = { ...baseOptions, autoElementScroll: true }
executeMock.mockResolvedValueOnce(100) // previous scroll position
const result = await takeElementScreenshot(browserInstance, optionsWithScroll, true)
expect(result).toEqual({
base64Image: 'bidi-screenshot-data',
isWebDriverElementScreenshot: false
})
// First call: scrollElementIntoView, second call: scrollToPosition (restore)
expect(executeMock).toHaveBeenCalledTimes(2)
expect(executeMock.mock.calls[0]).toMatchSnapshot()
expect(executeMock.mock.calls[1]).toMatchSnapshot()
expect(waitForSpy).toHaveBeenCalledWith(100)
})
it('should not restore scroll when autoElementScroll is enabled but no previous position', async () => {
const optionsWithScroll = { ...baseOptions, autoElementScroll: true }
executeMock.mockResolvedValueOnce(undefined) // no previous position
await takeElementScreenshot(browserInstance, optionsWithScroll, true)
// Only the scrollElementIntoView call, no restore
expect(executeMock).toHaveBeenCalledTimes(1)
expect(waitForSpy).toHaveBeenCalledWith(100)
})
it('should resolve a Promise-wrapped element (ChainablePromiseElement) before passing to browser.execute()', async () => {
const resolvedElement = { elementId: 'promise-element' }
const optionsWithPromiseElement = {
...baseOptions,
autoElementScroll: true,
element: Promise.resolve(resolvedElement) as any,
}
executeMock.mockResolvedValueOnce(100)
await takeElementScreenshot(browserInstance, optionsWithPromiseElement, true)
expect(getElementRectMock).toHaveBeenCalledWith('promise-element')
// The resolved element (not the Promise) must be passed to browser.execute()
expect(executeMock.mock.calls[0][1]).toEqual(resolvedElement)
})
})
describe('BiDi viewport screenshots', () => {
const vpOptions: ElementScreenshotDataOptions = {
...baseOptions,
biDiOrigin: 'viewport',
innerWidth: 1280,
innerHeight: 720,
}
it('should take viewport screenshot when element is fully inside the viewport', async () => {
// element at (10, 20, 100x200) — fits in 1280x720 viewport
const result = await takeElementScreenshot(browserInstance, vpOptions, true)
expect(result).toEqual({
base64Image: 'bidi-screenshot-data',
isWebDriverElementScreenshot: false,
})
expect(takeBase64BiDiScreenshotSpy).toHaveBeenCalledWith({
browserInstance,
origin: 'viewport',
clip: { x: 10, y: 20, width: 100, height: 200 },
})
})
it('should throw when element dimensions exceed the viewport', async () => {
getElementRectMock.mockResolvedValueOnce({ x: 0, y: 0, width: 1400, height: 800 })
const err = await takeElementScreenshot(browserInstance, vpOptions, true).catch(e => e) as Error
expect(err.message).toMatch(/element dimensions \(1400x800px\) exceed the viewport \(1280x720px\)/)
expect(err.message).toMatch(/biDiOrigin: 'document'/)
expect(err.message).toMatch(/composited layers/)
})
it('should throw when element is completely outside the viewport', async () => {
// element below the fold
getElementRectMock.mockResolvedValueOnce({ x: 0, y: 800, width: 100, height: 200 })
const err = await takeElementScreenshot(browserInstance, vpOptions, true).catch(e => e) as Error
expect(err.message).toMatch(/element is not in the viewport/)
expect(err.message).toMatch(/scrollIntoView/)
expect(err.message).toMatch(/autoElementScroll: true/)
})
it('should throw when element is partially outside the viewport but fits', async () => {
// element starts at x=-10, so it bleeds left of the viewport
getElementRectMock.mockResolvedValueOnce({ x: -10, y: 0, width: 100, height: 200 })
const err = await takeElementScreenshot(browserInstance, vpOptions, true).catch(e => e) as Error
expect(err.message).toMatch(/not fully visible in the viewport/)
expect(err.message).toMatch(/fits within the viewport/)
expect(err.message).toMatch(/autoElementScroll: true/)
})
it('should include element and viewport dimensions in the error messages', async () => {
getElementRectMock.mockResolvedValueOnce({ x: 0, y: 900, width: 200, height: 100 })
const err = await takeElementScreenshot(browserInstance, vpOptions, true).catch(e => e) as Error
expect(err.message).toMatch(/x=0, y=900, 200x100px/)
expect(err.message).toMatch(/viewport: 1280x720px/)
})
it('should scroll element into view before validating when autoElementScroll is true', async () => {
const vpScrollOptions: ElementScreenshotDataOptions = { ...vpOptions, autoElementScroll: true }
// After scroll, element is fully in viewport
executeMock.mockResolvedValueOnce(300) // previous scroll position
const result = await takeElementScreenshot(browserInstance, vpScrollOptions, true)
expect(result.base64Image).toBe('bidi-screenshot-data')
// scrollElementIntoView + scrollToPosition (restore)
expect(executeMock).toHaveBeenCalledTimes(2)
expect(takeBase64BiDiScreenshotSpy).toHaveBeenCalledWith(
expect.objectContaining({ origin: 'viewport' })
)
})
it('should use origin: document for the default (no biDiOrigin set)', async () => {
const defaultOptions = { ...vpOptions, biDiOrigin: undefined }
const result = await takeElementScreenshot(browserInstance, defaultOptions, true)
expect(result.base64Image).toBe('bidi-screenshot-data')
expect(takeBase64BiDiScreenshotSpy).toHaveBeenCalledWith(
expect.objectContaining({ origin: 'document' })
)
})
})
describe('Legacy screenshots', () => {
let logErrorSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
logErrorSpy = vi.spyOn(log, 'error').mockImplementation(() => {})
})
afterEach(() => {
vi.clearAllMocks()
logErrorSpy.mockRestore()
})
it('should take legacy screenshot when shouldUseBidi is false', async () => {
const result = await takeElementScreenshot(browserInstance, baseOptions, false)
expect(result).toEqual({
base64Image: 'cropped-screenshot-data',
isWebDriverElementScreenshot: false
})
expect(takeWebElementScreenshotSpy).toHaveBeenCalledWith({
addressBarShadowPadding: 6,
browserInstance,
devicePixelRatio: 2,
deviceRectangles: baseOptions.deviceRectangles,
element: baseOptions.element,
initialDevicePixelRatio: 2,
isEmulated: false,
innerHeight: 900,
isAndroid: false,
isAndroidChromeDriverScreenshot: false,
isAndroidNativeWebScreenshot: false,
isIOS: false,
isLandscape: false,
toolBarShadowPadding: 5,
fallback: false
})
expect(makeCroppedBase64ImageSpy).toHaveBeenCalledWith({
addIOSBezelCorners: false,
base64Image: 'web-element-screenshot-data',
deviceName: 'desktop',
devicePixelRatio: 2,
isWebDriverElementScreenshot: false,
isIOS: false,
isLandscape: false,
rectangles: { x: 0, y: 0, width: 100, height: 100 },
resizeDimensions: { top: 0, right: 0, bottom: 0, left: 0 }
})
expect(takeBase64BiDiScreenshotSpy).not.toHaveBeenCalled()
})
it('should handle auto scroll when enabled', async () => {
const optionsWithScroll = { ...baseOptions, autoElementScroll: true }
executeMock.mockResolvedValueOnce(100) // scroll position
const result = await takeElementScreenshot(browserInstance, optionsWithScroll, false)
expect(result).toEqual({
base64Image: 'cropped-screenshot-data',
isWebDriverElementScreenshot: false
})
expect(executeMock).toHaveBeenCalledTimes(2)
// First call for scrolling element into view
expect(executeMock.mock.calls[0]).toMatchSnapshot()
// Second call for scrolling back to original position
expect(executeMock.mock.calls[1]).toMatchSnapshot()
expect(waitForSpy).toHaveBeenCalledWith(100)
})
it('should not scroll back when autoElementScroll is enabled but no current position', async () => {
const optionsWithScroll = { ...baseOptions, autoElementScroll: true }
executeMock.mockResolvedValueOnce(undefined) // no scroll position returned
const result = await takeElementScreenshot(browserInstance, optionsWithScroll, false)
expect(result).toMatchSnapshot()
expect(executeMock).toHaveBeenCalledTimes(1) // Only the scroll into view call
expect(waitForSpy).toHaveBeenCalledWith(100)
})
it('should resolve a Promise-wrapped element (ChainablePromiseElement) before passing to browser.execute()', async () => {
const resolvedElement = { elementId: 'promise-element' }
const optionsWithPromiseElement = {
...baseOptions,
autoElementScroll: true,
element: Promise.resolve(resolvedElement) as any,
}
executeMock.mockResolvedValueOnce(100)
await takeElementScreenshot(browserInstance, optionsWithPromiseElement, false)
// The resolved element (not the Promise) must be passed to browser.execute()
expect(executeMock.mock.calls[0][1]).toEqual(resolvedElement)
// And also passed to takeWebElementScreenshot
expect(takeWebElementScreenshotSpy).toHaveBeenCalledWith(
expect.objectContaining({ element: resolvedElement })
)
})
it('should enable fallback when resizeDimensions is provided', async () => {
const optionsWithResize = {
...baseOptions,
resizeDimensions: { top: 10, right: 10, bottom: 10, left: 10 }
}
hasResizeDimensionsSpy.mockReturnValueOnce(true)
const result = await takeElementScreenshot(browserInstance, optionsWithResize, false)
expect(result).toMatchSnapshot()
expect(hasResizeDimensionsSpy).toHaveBeenCalledWith(optionsWithResize.resizeDimensions)
expect(takeWebElementScreenshotSpy).toHaveBeenCalledWith(
expect.objectContaining({
fallback: true
})
)
})
it('should enable fallback when device is emulated', async () => {
const optionsEmulated = { ...baseOptions, isEmulated: true }
const result = await takeElementScreenshot(browserInstance, optionsEmulated, false)
expect(result).toMatchSnapshot()
expect(takeWebElementScreenshotSpy).toHaveBeenCalledWith(
expect.objectContaining({
fallback: true
})
)
})
it('should disable fallback when no resizeDimensions and not emulated', async () => {
const optionsNoResize = {
...baseOptions,
resizeDimensions: undefined,
isEmulated: false
}
hasResizeDimensionsSpy.mockReturnValueOnce(false)
const result = await takeElementScreenshot(browserInstance, optionsNoResize, false)
expect(result).toMatchSnapshot()
expect(hasResizeDimensionsSpy).toHaveBeenCalledWith(undefined)
expect(takeWebElementScreenshotSpy).toHaveBeenCalledWith(
expect.objectContaining({
fallback: false
})
)
})
it('should handle zero dimensions by falling back to viewport size', async () => {
takeWebElementScreenshotSpy.mockResolvedValueOnce({
base64Image: 'web-element-screenshot-data',
rectangles: { x: 0, y: 0, width: 0, height: 0 },
isWebDriverElementScreenshot: false
})
const result = await takeElementScreenshot(browserInstance, baseOptions, false)
expect(result).toMatchSnapshot()
expect(getBase64ScreenshotSizeSpy).toHaveBeenCalledWith('web-element-screenshot-data')
expect(logErrorSpy.mock.calls).toMatchSnapshot()
expect(makeCroppedBase64ImageSpy).toHaveBeenCalledWith(
expect.objectContaining({
rectangles: { x: 0, y: 0, width: 100, height: 100 }
})
)
})
it('should handle zero width only', async () => {
takeWebElementScreenshotSpy.mockResolvedValueOnce({
base64Image: 'web-element-screenshot-data',
rectangles: { x: 50, y: 100, width: 0, height: 150 },
isWebDriverElementScreenshot: true
})
const result = await takeElementScreenshot(browserInstance, baseOptions, false)
expect(result).toMatchSnapshot()
expect(getBase64ScreenshotSizeSpy).toHaveBeenCalledWith('web-element-screenshot-data')
expect(logErrorSpy.mock.calls).toMatchSnapshot()
})
it('should handle zero height only', async () => {
takeWebElementScreenshotSpy.mockResolvedValueOnce({
base64Image: 'web-element-screenshot-data',
rectangles: { x: 50, y: 100, width: 150, height: 0 },
isWebDriverElementScreenshot: true
})
const result = await takeElementScreenshot(browserInstance, baseOptions, false)
expect(result).toMatchSnapshot()
expect(getBase64ScreenshotSizeSpy).toHaveBeenCalledWith('web-element-screenshot-data')
expect(logErrorSpy.mock.calls).toMatchSnapshot()
})
it('should pass correct WebDriver element screenshot flag', async () => {
takeWebElementScreenshotSpy.mockResolvedValueOnce({
base64Image: 'web-element-screenshot-data',
rectangles: { x: 0, y: 0, width: 100, height: 100 },
isWebDriverElementScreenshot: true
})
const result = await takeElementScreenshot(browserInstance, baseOptions, false)
expect(result).toEqual({
base64Image: 'cropped-screenshot-data',
isWebDriverElementScreenshot: true
})
expect(makeCroppedBase64ImageSpy).toHaveBeenCalledWith(
expect.objectContaining({
isWebDriverElementScreenshot: true
})
)
})
})
describe('Edge cases', () => {
it('should handle devicePixelRatio values and fallback to NaN when falsy', async () => {
const optionsWithValidDPR = { ...baseOptions, devicePixelRatio: 1 }
const result1 = await takeElementScreenshot(browserInstance, optionsWithValidDPR, false)
expect(result1).toMatchSnapshot()
expect(takeWebElementScreenshotSpy).toHaveBeenCalledWith(
expect.objectContaining({
devicePixelRatio: 1
})
)
expect(makeCroppedBase64ImageSpy).toHaveBeenCalledWith(
expect.objectContaining({
devicePixelRatio: 1
})
)
vi.clearAllMocks()
const optionsWithZeroDPR = { ...baseOptions, devicePixelRatio: 0 }
const result2 = await takeElementScreenshot(browserInstance, optionsWithZeroDPR, false)
expect(result2).toMatchSnapshot()
expect(takeWebElementScreenshotSpy).toHaveBeenCalledWith(
expect.objectContaining({
devicePixelRatio: 0
})
)
expect(makeCroppedBase64ImageSpy).toHaveBeenCalledWith(
expect.objectContaining({
devicePixelRatio: NaN
})
)
})
it('should handle undefined innerHeight', async () => {
const optionsWithUndefinedHeight = { ...baseOptions, innerHeight: undefined }
const result = await takeElementScreenshot(browserInstance, optionsWithUndefinedHeight, false)
expect(result).toMatchSnapshot()
expect(takeWebElementScreenshotSpy).toHaveBeenCalledWith(
expect.objectContaining({
innerHeight: undefined
})
)
})
it('should default shouldUseBidi to false when not provided', async () => {
const result = await takeElementScreenshot(browserInstance, baseOptions)
expect(result).toEqual({
base64Image: 'cropped-screenshot-data',
isWebDriverElementScreenshot: false
})
expect(takeBase64BiDiScreenshotSpy).not.toHaveBeenCalled()
expect(takeWebElementScreenshotSpy).toHaveBeenCalled()
})
})
})