-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
utils.ts
402 lines (317 loc) · 8.99 KB
/
utils.ts
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
import _ from 'lodash'
import capitalize from 'underscore.string/capitalize'
import methods from 'methods'
import dayjs from 'dayjs'
import $ from 'jquery'
import $dom from '../dom'
import $jquery from '../dom/jquery'
import { $Location } from './location'
const tagOpen = /\[([a-z\s='"-]+)\]/g
const tagClosed = /\[\/([a-z]+)\]/g
const defaultOptions = {
delay: 10,
force: false,
timeout: null,
interval: null,
multiple: false,
waitForAnimations: true,
animationDistanceThreshold: 5,
scrollBehavior: 'top',
}
const USER_FRIENDLY_TYPE_DETECTORS = _.map([
[_.isUndefined, 'undefined'],
[_.isNull, 'null'],
[_.isBoolean, 'boolean'],
[_.isNumber, 'number'],
[_.isString, 'string'],
[_.isRegExp, 'regexp'],
[_.isSymbol, 'symbol'],
[_.isElement, 'element'],
[_.isError, 'error'],
[_.isSet, 'set'],
[_.isWeakSet, 'set'],
[_.isMap, 'map'],
[_.isWeakMap, 'map'],
[_.isFunction, 'function'],
[_.isArrayLikeObject, 'array'],
[_.isBuffer, 'buffer'],
[_.isDate, 'date'],
[_.isObject, 'object'],
[_.stubTrue, 'unknown'],
], ([fn, type]) => {
return [fn, _.constant(type)]
}) as [(val: any) => boolean, (val: Function) => Function][]
export default {
warning (msg) {
// eslint-disable-next-line no-console
return console.warn(`Cypress Warning: ${msg}`)
},
log (...msgs) {
// eslint-disable-next-line no-console
return console.log(...msgs)
},
monkeypatchBefore (origFn, fn) {
return function () {
const newArgs = fn.apply(this, arguments)
if (newArgs !== undefined) {
return origFn.apply(this, newArgs)
}
return origFn.apply(this, arguments)
}
},
unwrapFirst (val) {
// this method returns the first item in an array
// and if its still a jquery object, then we return
// the first() jquery element
const item = [].concat(val)[0]
if ($jquery.isJquery(item)) {
return (item as JQuery<any>).first()
}
return item
},
switchCase (value, casesObj, defaultKey = 'default') {
if (_.has(casesObj, value)) {
return _.result(casesObj, value)
}
if (_.has(casesObj, defaultKey)) {
return _.result(casesObj, defaultKey)
}
const keys = _.keys(casesObj)
throw new Error(`The switch/case value: '${value}' did not match any cases: ${keys.join(', ')}.`)
},
reduceProps (obj, props: string[] = []) {
if (!obj) {
return null
}
return _.reduce(props, (memo, prop) => {
if (_.has(obj, prop) || obj[prop] !== undefined) {
memo[prop] = _.result(obj, prop)
}
return memo
}, {})
},
normalizeObjWithLength (obj) {
// lodash shits the bed if our object has a 'length'
// property so we have to normalize that
if (_.has(obj, 'length')) {
obj.Length = obj.length
delete obj.length
}
return obj
},
// return a new object if the obj
// contains the properties of filter
// and the values are different
filterOutOptions (obj, filter = {}) {
_.defaults(filter, defaultOptions)
this.normalizeObjWithLength(filter)
const whereFilterHasSameKeyButDifferentValue = (value, key) => {
const upperKey = capitalize(key)
return (_.has(filter, key) || _.has(filter, upperKey)) &&
filter[key] !== value
}
obj = _.pickBy(obj, whereFilterHasSameKeyButDifferentValue)
if (_.isEmpty(obj)) {
return undefined
}
return obj
},
stringifyActualObj (obj) {
obj = this.normalizeObjWithLength(obj)
const str = _.reduce(obj, (memo, value, key) => {
memo.push(`${`${key}`.toLowerCase()}: ${this.stringifyActual(value)}`)
return memo
}, [] as string[])
return `{${str.join(', ')}}`
},
stringifyActual (value) {
if ($dom.isDom(value)) {
return $dom.stringify(value, 'short')
}
if (_.isFunction(value)) {
return 'function(){}'
}
if (_.isArray(value)) {
const len = value.length
if (len > 3) {
return `Array[${len}]`
}
return `[${_.map(value, _.bind(this.stringifyActual, this)).join(', ')}]`
}
if (_.isRegExp(value)) {
return value.toString()
}
if (_.isObject(value)) {
// Cannot use $dom.isJquery here because it causes infinite recursion.
if (value instanceof $) {
return `jQuery{${(value as JQueryStatic).length}}`
}
const len = _.keys(value).length
if (len > 2) {
return `Object{${len}}`
}
try {
return this.stringifyActualObj(value)
} catch (err) {
return String(value)
}
}
if (_.isSymbol(value)) {
return 'Symbol'
}
if (_.isUndefined(value)) {
return undefined
}
return `${value}`
},
// give us some user-friendly "types"
stringifyFriendlyTypeof: _.cond(USER_FRIENDLY_TYPE_DETECTORS),
stringify (values) {
// if we already have an array
// then nest it again so that
// its formatted properly
values = [].concat(values)
return _
.chain(values)
.map(_.bind(this.stringifyActual, this))
.without(undefined)
.join(', ')
.value()
},
stringifyArg (arg) {
if (_.isString(arg) || _.isNumber(arg) || _.isBoolean(arg)) {
return JSON.stringify(arg)
}
if (_.isNull(arg)) {
return 'null'
}
if (_.isUndefined(arg)) {
return 'undefined'
}
return this.stringifyActual(arg)
},
plural (obj, plural, singular) {
obj = _.isNumber(obj) ? obj : obj.length
if (obj > 1) {
return plural
}
return singular
},
convertHtmlTags (html) {
return html
.replace(tagOpen, '<$1>')
.replace(tagClosed, '</$1>')
},
isInstanceOf (instance, constructor) {
try {
return instance instanceof constructor
} catch (e) {
return false
}
},
normalizeNumber (num) {
const parsed = Number(num)
// return num if this isNaN else return parsed
if (_.isNaN(parsed)) {
return num
}
return parsed
},
isValidHttpMethod (str) {
return _.isString(str) && _.includes(methods, str.toLowerCase())
},
addTwentyYears () {
return dayjs().add(20, 'year').unix()
},
locReload (forceReload, win) {
return win.location.reload(forceReload)
},
locHref (url, win) {
win.location.href = url
},
locToString (win) {
return win.location.toString()
},
locExisting () {
return $Location.create(window.location.href)
},
iframeSrc ($autIframe, url) {
return $autIframe.prop('src', url)
},
getDistanceBetween (point1, point2) {
const deltaX = point1.x - point2.x
const deltaY = point1.y - point2.y
return Math.sqrt((deltaX * deltaX) + (deltaY * deltaY))
},
getTestFromRunnable (r) {
return r.ctx.currentTest || r
},
memoize (func, cacheInstance = new Map()) {
const memoized = function (...args) {
const key = args[0]
const { cache } = memoized
if (cache.has(key)) {
return cache.get(key)
}
const result = func.apply(this, args)
memoized.cache = cache.set(key, result) || cache
return result
}
memoized.cache = cacheInstance
return memoized
},
indent (str, indentAmount) {
const indentStr = _.repeat(' ', indentAmount)
str = str.replace(/\n/g, `\n${indentStr}`)
return `${indentStr}${str}`
},
// normalize more than {maxNewLines} new lines into
// exactly {replacementNumLines} new lines
normalizeNewLines (str, maxNewLines, replacementNumLines?) {
const moreThanMaxNewLinesRe = new RegExp(`\\n{${maxNewLines},}`)
const replacementWithNumLines = replacementNumLines ?? maxNewLines
return _.chain(str)
.split(moreThanMaxNewLinesRe)
.compact()
.join(_.repeat('\n', replacementWithNumLines))
.value()
},
/**
* Correctly decodes Unicode string in encoded in base64
* @see https://github.com/cypress-io/cypress/issues/5435
* @see https://github.com/cypress-io/cypress/issues/7507
* @see https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
*
* @example
```
Buffer.from(JSON.stringify({state: '🙂'})).toString('base64')
// 'eyJzdGF0ZSI6IvCfmYIifQ=='
// "window.atob" does NOT work
// atob('eyJzdGF0ZSI6IvCfmYIifQ==')
// "{"state":"ð"}"
// but this function works
b64DecodeUnicode('eyJzdGF0ZSI6IvCfmYIifQ==')
'{"state":"🙂"}'
```
*/
decodeBase64Unicode (str) {
return decodeURIComponent(atob(str).split('').map((char) => {
return `%${(`00${char.charCodeAt(0).toString(16)}`).slice(-2)}`
}).join(''))
},
/**
* Correctly encodes Unicode string to base64
* @see https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
*/
encodeBase64Unicode (str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => {
return String.fromCharCode(Number(`0x${p1}`))
}))
},
noArgsAreAFunction (args) {
return !_.some(args, _.isFunction)
},
isPromiseLike (ret) {
return ret && _.isFunction(ret.then)
},
}