forked from cypress-io/cypress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ensures.ts
428 lines (349 loc) · 10.9 KB
/
ensures.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
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
import _ from 'lodash'
import $dom from '../dom'
import $utils from '../cypress/utils'
import $errUtils from '../cypress/error_utils'
import $elements from '../dom/elements'
import type { StateFunc } from '../cypress/state'
import type { $Cy } from '../cypress/cy'
const VALID_POSITIONS = 'topLeft top topRight left center right bottomLeft bottom bottomRight'.split(' ')
// TODO: in 4.0 we should accept a new validation type called 'elements'
// which accepts an array of elements (and they all have to be elements!!)
// this would fix the TODO below, and also ensure that commands understand
// they may need to work with both element arrays, or specific items
// such as a single element, a single document, or single window
let returnFalse = () => false
export const create = (state: StateFunc, expect: $Cy['expect']) => {
// TODO: we should probably normalize all subjects
// into an array and loop through each and verify
// each element in the array is valid. as it stands
// we only validate the first
const validateType = (subject, type, cmd) => {
const name = cmd.get('name')
switch (type) {
case 'element':
// if this is an element then ensure its currently attached
// to its document context
if ($dom.isElement(subject)) {
ensureAttached(subject, name)
}
// always ensure this is an element
return ensureElement(subject, name)
case 'document':
return ensureDocument(subject, name)
case 'window':
return ensureWindow(subject, name)
default:
return
}
}
const ensureSubjectByType = (subject, type) => {
const current = state('current')
let types: string[] = [].concat(type)
// if we have an optional subject and nothing's
// here then just return cuz we good to go
if (types.includes('optional') && _.isUndefined(subject)) {
return
}
// okay we either have a subject and either way
// slice out optional so we can verify against
// the various types
types = _.without(types, 'optional')
// if we have no types then bail
if (types.length === 0) {
return
}
let err
const errors: Error[] = []
for (type of types) {
try {
validateType(subject, type, current)
} catch (error) {
err = error
errors.push(err)
}
}
// every validation failed and we had more than one validation
if (errors.length === types.length) {
err = errors[0]
if (types.length > 1) {
// append a nice error message telling the user this
const errProps = $errUtils.appendErrMsg(err, `All ${types.length} subject validations failed on this subject.`)
$errUtils.mergeErrProps(err, errProps)
}
throw err
}
}
const ensureRunnable = (name) => {
if (!state('runnable')) {
$errUtils.throwErrByPath('miscellaneous.outside_test_with_cmd', {
args: {
cmd: name,
},
})
}
}
const ensureElementIsNotAnimating = ($el, coords = [], threshold) => {
const lastTwo = coords.slice(-2)
// bail if we dont yet have two points
if (lastTwo.length !== 2) {
$errUtils.throwErrByPath('dom.animation_check_failed')
}
const [point1, point2] = lastTwo
// verify that there is not a distance
// greater than a default of '5' between
// the points
if ($utils.getDistanceBetween(point1, point2) > threshold) {
const cmd = state('current').get('name')
const node = $dom.stringify($el)
$errUtils.throwErrByPath('dom.animating', {
args: { cmd, node },
})
}
}
const ensureNotDisabled = (subject, onFail) => {
const cmd = state('current').get('name')
if (subject.prop('disabled')) {
const node = $dom.stringify(subject)
$errUtils.throwErrByPath('dom.disabled', {
onFail,
args: { cmd, node },
})
}
}
const ensureNotReadonly = (subject, onFail) => {
const cmd = state('current').get('name')
// readonly can only be applied to input/textarea
// not on checkboxes, radios, etc..
if ($dom.isTextLike(subject.get(0)) && subject.prop('readonly')) {
const node = $dom.stringify(subject)
$errUtils.throwErrByPath('dom.readonly', {
onFail,
args: { cmd, node },
})
}
}
const runVisibilityCheck = (subject, onFail, method) => {
const visibleSubjects = subject.filter(function () {
return !method(this, 'isVisible()', { checkOpacity: false })
})
if (subject.length !== visibleSubjects.length) {
const cmd = state('current').get('name')
const reason = $dom.getReasonIsHidden(subject, { checkOpacity: false })
const node = $dom.stringify(subject)
$errUtils.throwErrByPath('dom.not_visible', {
onFail,
args: { cmd, node, reason },
})
}
}
const ensureVisibility = (subject, onFail) => {
return runVisibilityCheck(subject, onFail, $dom.isHidden)
}
const ensureStrictVisibility = (subject, onFail) => {
return runVisibilityCheck(subject, onFail, $dom.isStrictlyHidden)
}
const ensureNotHiddenByAncestors = (subject, onFail) => {
return runVisibilityCheck(subject, onFail, $dom.isHiddenByAncestors)
}
const ensureAttached = (subject, name, onFail?) => {
if ($dom.isDetached(subject)) {
const current = state('current')
const cmd = name ?? current.get('name')
const prev = current.get('prev') ? current.get('prev').get('name') : current.get('name')
const node = $dom.stringify(subject)
$errUtils.throwErrByPath('subject.not_attached', {
onFail,
args: { cmd, prev, node },
})
}
}
const ensureElement = (subject, name, onFail?) => {
if (!$dom.isElement(subject)) {
const prev = state('current').get('prev')
$errUtils.throwErrByPath('subject.not_element', {
onFail,
args: {
name,
subject: $utils.stringifyActual(subject),
previous: prev.get('name'),
},
})
}
}
const ensureWindow = (subject, name) => {
if (!$dom.isWindow(subject)) {
const prev = state('current').get('prev')
$errUtils.throwErrByPath('subject.not_window_or_document', {
args: {
name,
type: 'window',
subject: $utils.stringifyActual(subject),
previous: prev.get('name'),
},
})
}
}
const ensureDocument = (subject, name) => {
if (!$dom.isDocument(subject)) {
const prev = state('current').get('prev')
$errUtils.throwErrByPath('subject.not_window_or_document', {
args: {
name,
type: 'document',
subject: $utils.stringifyActual(subject),
previous: prev.get('name'),
},
})
}
}
const ensureExistence = (subject) => {
returnFalse = () => {
cleanup()
return false
}
const cleanup = () => {
return state('onBeforeLog', null)
}
// prevent any additional logs this is an implicit assertion
state('onBeforeLog', returnFalse)
// verify the $el exists and use our default error messages
// TODO: always unbind if our expectation failed
try {
expect(subject).to.exist
} catch (err) {
cleanup()
throw err
}
}
const ensureElExistence = ($el) => {
// dont throw if this isnt even a DOM object
// return if not $dom.isJquery($el)
// ensure that we either had some assertions
// or that the element existed
if ($el && $el.length) {
return
}
// TODO: REFACTOR THIS TO CALL THE CHAI-OVERRIDES DIRECTLY
// OR GO THROUGH I18N
return ensureExistence($el)
}
const ensureElDoesNotHaveCSS = ($el, cssProperty, cssValue, onFail) => {
const cmd = state('current').get('name')
const el = $el[0]
const win = $dom.getWindowByElement(el)
const value = win.getComputedStyle(el)[cssProperty]
if (value === cssValue) {
const elInherited = $elements.findParent(el, (el, prevEl) => {
if (win.getComputedStyle(el)[cssProperty] !== cssValue) {
return prevEl
}
})
const element = $dom.stringify(el)
const elementInherited = (el !== elInherited) && $dom.stringify(elInherited)
const consoleProps = {
'But it has CSS': `${cssProperty}: ${cssValue}`,
}
if (elementInherited) {
_.extend(consoleProps, {
'Inherited From': elInherited,
})
}
$errUtils.throwErrByPath('dom.pointer_events_none', {
onFail,
args: {
cmd,
element,
elementInherited,
},
errProps: {
consoleProps,
},
})
}
}
const ensureDescendents = ($el1, $el2, onFail) => {
const cmd = state('current').get('name')
if (!$dom.isDescendent($el1, $el2)) {
// https://github.com/cypress-io/cypress/issues/18008
// when an element inside a shadow root is covered by its shadow host
if (
$dom.isWithinShadowRoot($el1.get(0)) &&
$el1.get(0).getRootNode() === $el2?.get(0).shadowRoot
) {
return
}
if ($el2) {
const element1 = $dom.stringify($el1)
const element2 = $dom.stringify($el2)
$errUtils.throwErrByPath('dom.covered', {
onFail,
args: { cmd, element1, element2 },
errProps: {
consoleProps: {
'But its Covered By': $dom.getElements($el2),
},
},
})
}
const node = $dom.stringify($el1)
$errUtils.throwErrByPath('dom.center_hidden', {
onFail,
args: { cmd, node },
errProps: {
consoleProps: {
'But its Covered By': $dom.getElements($el2),
},
},
})
}
}
const ensureValidPosition = (position, log): true | void => {
// make sure its valid first!
if (VALID_POSITIONS.includes(position)) {
return true
}
$errUtils.throwErrByPath('dom.invalid_position_argument', {
onFail: log,
args: {
position,
validPositions: VALID_POSITIONS.join(', '),
},
})
}
const ensureScrollability = ($el, cmd): true | void => {
if ($dom.isScrollable($el)) {
return true
}
// prep args to throw in error since we can't scroll
cmd = cmd ?? state('current').get('name')
const node = $dom.stringify($el)
$errUtils.throwErrByPath('dom.not_scrollable', {
args: { cmd, node },
})
}
return {
ensureElement,
ensureAttached,
ensureWindow,
ensureDocument,
ensureElDoesNotHaveCSS,
ensureElementIsNotAnimating,
ensureNotDisabled,
ensureVisibility,
ensureStrictVisibility,
ensureNotHiddenByAncestors,
ensureExistence,
ensureElExistence,
ensureDescendents,
ensureValidPosition,
ensureScrollability,
ensureNotReadonly,
// internal functions
ensureSubjectByType,
ensureRunnable,
}
}
export interface IEnsures extends Omit<
ReturnType<typeof create>,
'ensureSubjectByType' | 'ensureRunnable'
> {}