forked from vitest-dev/vitest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtester-utils.ts
More file actions
320 lines (289 loc) · 9.64 KB
/
tester-utils.ts
File metadata and controls
320 lines (289 loc) · 9.64 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
import type { Locator, SelectorOptions, UserEventWheelDeltaOptions, UserEventWheelOptions } from 'vitest/browser'
import type { BrowserRPC } from '../client'
import { getBrowserState, getWorkerState } from '../utils'
/* @__NO_SIDE_EFFECTS__ */
export function convertElementToCssSelector(element: Element): string {
if (!element || !(element instanceof Element)) {
throw new Error(
`Expected DOM element to be an instance of Element, received ${typeof element}`,
)
}
return getUniqueCssSelector(element)
}
function escapeIdForCSSSelector(id: string) {
return id
.split('')
.map((char) => {
const code = char.charCodeAt(0)
if (char === ' ' || char === '#' || char === '.' || char === ':' || char === '[' || char === ']' || char === '>' || char === '+' || char === '~' || char === '\\') {
// Escape common special characters with backslashes
return `\\${char}`
}
else if (code >= 0x10000) {
// Unicode escape for characters outside the BMP
return `\\${code.toString(16).toUpperCase().padStart(6, '0')} `
}
else if (code < 0x20 || code === 0x7F) {
// Non-printable ASCII characters (0x00-0x1F and 0x7F) are escaped
return `\\${code.toString(16).toUpperCase().padStart(2, '0')} `
}
else if (code >= 0x80) {
// Non-ASCII characters (0x80 and above) are escaped
return `\\${code.toString(16).toUpperCase().padStart(2, '0')} `
}
else {
// Allowable characters are used directly
return char
}
})
.join('')
}
function getUniqueCssSelector(el: Element) {
const path = []
let parent: null | ParentNode
let hasShadowRoot = false
// eslint-disable-next-line no-cond-assign
while (parent = getParent(el)) {
if ((parent as Element).shadowRoot) {
hasShadowRoot = true
}
const tag = el.tagName
if (el.id) {
path.push(`#${escapeIdForCSSSelector(el.id)}`)
}
else if (!el.nextElementSibling && !el.previousElementSibling) {
path.push(tag.toLowerCase())
}
else {
let index = 0
let sameTagSiblings = 0
let elementIndex = 0
for (const sibling of parent.children) {
index++
if (sibling.tagName === tag) {
sameTagSiblings++
}
if (sibling === el) {
elementIndex = index
}
}
if (sameTagSiblings > 1) {
path.push(`${tag.toLowerCase()}:nth-child(${elementIndex})`)
}
else {
path.push(tag.toLowerCase())
}
}
el = parent as Element
};
return `${getBrowserState().provider === 'webdriverio' && hasShadowRoot ? '>>>' : ''}${path.reverse().join(' > ')}`
}
function getParent(el: Element) {
const parent = el.parentNode
if (parent instanceof ShadowRoot) {
return parent.host
}
return parent
}
const ACTION_TRACE_COMMANDS = new Set([
'__vitest_click',
'__vitest_dblClick',
'__vitest_tripleClick',
'__vitest_wheel',
'__vitest_type',
'__vitest_clear',
'__vitest_fill',
'__vitest_selectOptions',
'__vitest_dragAndDrop',
'__vitest_hover',
'__vitest_upload',
'__vitest_tab',
'__vitest_keyboard',
'__vitest_takeScreenshot',
])
export class CommandsManager {
private _listeners: ((command: string, args: any[]) => void)[] = []
public onCommand(listener: (command: string, args: any[]) => void): void {
this._listeners.push(listener)
}
public async triggerCommand<T>(
command: string,
args: any[],
// error makes sure the stack trace is correct on webkit,
// if we make the error here, it looses the context
clientError: Error = new Error('empty'),
): Promise<T> {
const state = getWorkerState()
const rpc = state.rpc as any as BrowserRPC
const { sessionId, traces } = getBrowserState()
const filepath = state.filepath || state.current?.file?.filepath
args = args.filter(arg => arg !== undefined) // remove optional fields
const actionTraceGroupName = ACTION_TRACE_COMMANDS.has(command) ? command : undefined
const currentTest = getWorkerState().current
const shouldMarkTrace = actionTraceGroupName
&& !!currentTest
&& getBrowserState().activeTraceTaskIds.has(currentTest.id)
if (this._listeners.length) {
await Promise.all(this._listeners.map(listener => listener(command, args)))
}
return traces.$(
'vitest.browser.tester.command',
{
attributes: {
'vitest.browser.command': command,
'code.file.path': filepath,
},
},
async () => {
if (shouldMarkTrace) {
await rpc.triggerCommand<void>(
sessionId,
'__vitest_groupTraceStart',
filepath,
[{
name: actionTraceGroupName,
stack: clientError.stack,
}],
)
}
try {
return await rpc.triggerCommand<T>(sessionId, command, filepath, args)
}
catch (err: any) {
// rethrow an error to keep the stack trace in browser
clientError.message = err.message
clientError.name = err.name
clientError.stack = clientError.stack?.replace(clientError.message, err.message)
throw clientError
}
finally {
if (shouldMarkTrace) {
await rpc.triggerCommand<void>(
sessionId,
'__vitest_groupTraceEnd',
filepath,
[],
)
}
}
},
)
}
}
const now = globalThis.performance
? globalThis.performance.now.bind(globalThis.performance)
: Date.now
export function processTimeoutOptions<T extends { timeout?: number }>(options_: T | undefined): T | undefined {
if (
// if timeout is set, keep it
(options_ && options_.timeout != null)
) {
return options_
}
// if there is a default action timeout, use it
if (getWorkerState().config.browser.providerOptions.actionTimeout != null) {
return options_
}
const runner = getBrowserState().runner
const startTime = runner._currentTaskStartTime
// ignore timeout if this is called outside of a test
if (!startTime) {
return options_
}
const timeout = runner._currentTaskTimeout
if (timeout === 0 || timeout == null || timeout === Number.POSITIVE_INFINITY) {
return options_
}
options_ = options_ || {} as T
const currentTime = now()
const endTime = startTime + timeout
const remainingTime = Math.floor(endTime - currentTime)
if (remainingTime <= 0) {
return options_
}
// give us some time to process the timeout
options_.timeout = remainingTime - 100
return options_
}
export function getIframeScale(): number {
const testerUi = window.parent.document.querySelector(`iframe[data-vitest]`)?.parentElement
if (!testerUi) {
throw new Error(`Cannot find Tester element. This is a bug in Vitest. Please, open a new issue with reproduction.`)
}
const scaleAttribute = testerUi.getAttribute('data-scale')
const scale = Number(scaleAttribute)
if (Number.isNaN(scale)) {
throw new TypeError(`Cannot parse scale value from Tester element (${scaleAttribute}). This is a bug in Vitest. Please, open a new issue with reproduction.`)
}
return scale
}
function escapeRegexForSelector(re: RegExp): string {
// Unicode mode does not allow "identity character escapes", so we do not escape and
// hope that it does not contain quotes and/or >> signs.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape
// TODO: rework RE usages in internal selectors away from literal representation to json, e.g. {source,flags}.
if (re.unicode || (re as any).unicodeSets) {
return String(re)
}
// Even number of backslashes followed by the quote -> insert a backslash.
return String(re).replace(/(^|[^\\])(\\\\)*(["'`])/g, '$1$2\\$3').replace(/>>/g, '\\>\\>')
}
export function escapeForTextSelector(text: string | RegExp, exact: boolean): string {
if (typeof text !== 'string') {
return escapeRegexForSelector(text)
}
return `${JSON.stringify(text)}${exact ? 's' : 'i'}`
}
const provider = getBrowserState().provider
const kElementLocator = Symbol.for('$$vitest:locator-resolved')
export async function convertToSelector(elementOrLocator: Element | Locator, options?: SelectorOptions): Promise<string> {
if (!elementOrLocator) {
throw new Error('Expected element or locator to be defined.')
}
if (elementOrLocator instanceof Element) {
return convertElementToCssSelector(elementOrLocator)
}
if (isLocator(elementOrLocator)) {
if (provider === 'playwright' || kElementLocator in elementOrLocator) {
return elementOrLocator.selector
}
const element = await elementOrLocator.findElement(options)
return convertElementToCssSelector(element)
}
throw new Error('Expected element or locator to be an instance of Element or Locator.')
}
const kLocator = Symbol.for('$$vitest:locator')
export function isLocator(element: unknown): element is Locator {
return (!!element && typeof element === 'object' && kLocator in element)
}
const DEFAULT_WHEEL_DELTA = 100
export function resolveUserEventWheelOptions(options: UserEventWheelOptions): UserEventWheelDeltaOptions {
let delta: UserEventWheelDeltaOptions['delta']
if (options.delta) {
delta = options.delta
}
else {
switch (options.direction) {
case 'up': {
delta = { y: -DEFAULT_WHEEL_DELTA }
break
}
case 'down': {
delta = { y: DEFAULT_WHEEL_DELTA }
break
}
case 'left': {
delta = { x: -DEFAULT_WHEEL_DELTA }
break
}
case 'right': {
delta = { x: DEFAULT_WHEEL_DELTA }
break
}
}
}
return {
delta,
times: options.times,
}
}