How to use addCssAnimationDisabler method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

dom.js

Source: dom.js Github

copy
1import _ from 'lodash'
2import { $ } from '@packages/driver'
3import Promise from 'bluebird'
4
5import selectorPlaygroundHighlight from '../selector-playground/highlight'
6
7const styles = (styleString) => {
8  return styleString.replace(/\s*\n\s*/g, '')
9}
10
11const resetStyles = `
12  border: none !important;
13  margin: 0 !important;
14  padding: 0 !important;
15`
16
17function addHitBoxLayer (coords, body) {
18  if (body == null) {
19    body = $('body')
20  }
21
22  const height = 10
23  const width = 10
24
25  const dotHeight = 4
26  const dotWidth = 4
27
28  const top = coords.y - height / 2
29  const left = coords.x - width / 2
30
31  const dotTop = height / 2 - dotHeight / 2
32  const dotLeft = width / 2 - dotWidth / 2
33
34  const boxStyles = styles(`
35    ${resetStyles}
36    position: absolute;
37    top: ${top}px;
38    left: ${left}px;
39    width: ${width}px;
40    height: ${height}px;
41    background-color: red;
42    border-radius: 5px;
43    box-shadow: 0 0 5px #333;
44    z-index: 2147483647;
45  `)
46  const box = $(`<div class="__cypress-highlight" style="${boxStyles}" />`)
47  const wrapper = $(`<div style="${styles(resetStyles)} position: relative" />`).appendTo(box)
48  const dotStyles = styles(`
49    ${resetStyles}
50    position: absolute;
51    top: ${dotTop}px;
52    left: ${dotLeft}px;
53    height: ${dotHeight}px;
54    width: ${dotWidth}px;
55    height: ${dotHeight}px;
56    background-color: pink;
57    border-radius: 5px;
58  `)
59  $(`<div style="${dotStyles}">`).appendTo(wrapper)
60
61  return box.appendTo(body)
62}
63
64function addElementBoxModelLayers ($el, body) {
65  if (body == null) {
66    body = $('body')
67  }
68
69  const dimensions = getElementDimensions($el)
70
71  const container = $('<div class="__cypress-highlight">')
72
73  const layers = {
74    Content: '#9FC4E7',
75    Padding: '#C1CD89',
76    Border: '#FCDB9A',
77    Margin: '#F9CC9D',
78  }
79
80  // create the margin / bottom / padding layers
81  _.each(layers, (color, attr) => {
82    let obj
83    switch (attr) {
84      case 'Content':
85        // rearrange the contents offset so
86        // its inside of our border + padding
87        obj = {
88          width: dimensions.width,
89          height: dimensions.height,
90          top: dimensions.offset.top + dimensions.borderTop + dimensions.paddingTop,
91          left: dimensions.offset.left + dimensions.borderLeft + dimensions.paddingLeft,
92        }
93        break
94      default:
95        obj = {
96          width: getDimensionsFor(dimensions, attr, 'width'),
97          height: getDimensionsFor(dimensions, attr, 'height'),
98          top: dimensions.offset.top,
99          left: dimensions.offset.left,
100        }
101    }
102
103    // if attr is margin then we need to additional
104    // subtract what the actual marginTop + marginLeft
105    // values are, since offset disregards margin completely
106    if (attr === 'Margin') {
107      obj.top -= dimensions.marginTop
108      obj.left -= dimensions.marginLeft
109    }
110
111    // bail if the dimensions of this layer match the previous one
112    // so we dont create unnecessary layers
113    if (dimensionsMatchPreviousLayer(obj, container)) return
114
115    return createLayer($el, attr, color, container, obj)
116  })
117
118  container.appendTo(body)
119
120  container.children().each((index, el) => {
121    const $el = $(el)
122    const top = $el.data('top')
123    const left = $el.data('left')
124
125    // dont ask... for some reason we
126    // have to run offset twice!
127    _.times(2, () => $el.offset({ top, left }))
128  })
129
130  return container
131}
132
133function getOrCreateSelectorHelperDom ($body) {
134  let $container = $body.find('.__cypress-selector-playground')
135
136  if ($container.length) {
137    const shadowRoot = $container.find('.__cypress-selector-playground-shadow-root-container')[0].shadowRoot
138
139    return Promise.resolve({
140      $container,
141      shadowRoot,
142      $reactContainer: $(shadowRoot).find('.react-container'),
143      $cover: $container.find('.__cypress-selector-playground-cover'),
144    })
145  }
146
147  $container = $('<div />')
148  .addClass('__cypress-selector-playground')
149  .css({ position: 'static' })
150  .appendTo($body)
151
152  const $shadowRootContainer = $('<div />')
153  .addClass('__cypress-selector-playground-shadow-root-container')
154  .css({ position: 'static' })
155  .appendTo($container)
156
157  const shadowRoot = $shadowRootContainer[0].attachShadow({ mode: 'open' })
158
159  const $reactContainer = $('<div />')
160  .addClass('react-container')
161  .appendTo(shadowRoot)
162
163  const $cover = $('<div />')
164  .addClass('__cypress-selector-playground-cover')
165  .appendTo($container)
166
167  return Promise.try(() => fetch('/__cypress/runner/cypress_selector_playground.css'))
168  .then((result) => {
169    return result.text()
170  })
171  .then((content) => {
172    $('<style />', { html: content }).prependTo(shadowRoot)
173    return { $container, shadowRoot, $reactContainer, $cover }
174  })
175  .catch((error) => {
176    console.error('Selector playground failed to load styles:', error) // eslint-disable-line no-console
177    return { $container, shadowRoot, $reactContainer, $cover }
178  })
179}
180
181function addOrUpdateSelectorPlaygroundHighlight ({ $el, $body, selector, showTooltip, onClick }) {
182  getOrCreateSelectorHelperDom($body)
183  .then(({ $container, shadowRoot, $reactContainer, $cover }) => {
184    if (!$el) {
185      selectorPlaygroundHighlight.unmount($reactContainer[0])
186      $cover.off('click')
187      $container.remove()
188      return
189    }
190
191    const borderSize = 2
192
193    const styles = $el.map((__, el) => {
194      const $el = $(el)
195      const offset = $el.offset()
196
197      return {
198        position: 'absolute',
199        margin: 0,
200        padding: 0,
201        width: $el.outerWidth(),
202        height: $el.outerHeight(),
203        top: offset.top - borderSize,
204        left: offset.left - borderSize,
205        transform: $el.css('transform'),
206        zIndex: getZIndex($el),
207      }
208    }).get()
209
210    if (styles.length === 1) {
211      $cover
212      .css(styles[0])
213      .off('click')
214      .on('click', onClick)
215    }
216
217    selectorPlaygroundHighlight.render($reactContainer[0], {
218      selector,
219      appendTo: shadowRoot,
220      boundary: $body[0],
221      showTooltip,
222      styles,
223    })
224  })
225}
226
227function createLayer ($el, attr, color, container, dimensions) {
228  const transform = $el.css('transform')
229
230  const css = {
231    transform,
232    width: dimensions.width,
233    height: dimensions.height,
234    position: 'absolute',
235    zIndex: getZIndex($el),
236    backgroundColor: color,
237    opacity: 0.6,
238  }
239
240  return $('<div>')
241  .css(css)
242  .attr('data-top', dimensions.top)
243  .attr('data-left', dimensions.left)
244  .attr('data-layer', attr)
245  .prependTo(container)
246}
247
248function dimensionsMatchPreviousLayer (obj, container) {
249  // since we're prepending to the container that
250  // means the previous layer is actually the first child element
251  const previousLayer = container.children().first()
252
253  // bail if there is no previous layer
254  if (!previousLayer.length) { return }
255
256  return obj.width === previousLayer.width() &&
257  obj.height === previousLayer.height()
258}
259
260function getDimensionsFor (dimensions, attr, dimension) {
261  return dimensions[`${dimension}With${attr}`]
262}
263
264function getZIndex (el) {
265  if (/^(auto|0)$/.test(el.css('zIndex'))) {
266    return 2147483647
267  } else {
268    return _.toNumber(el.css('zIndex'))
269  }
270}
271
272function getElementDimensions (el) {
273  const dimensions = {
274    offset: el.offset(), // offset disregards margin but takes into account border + padding
275    height: el.height(), // we want to use height here (because that always returns just the content hight) instead of .css() because .css('height') is altered based on whether box-sizing: border-box is set
276    width: el.width(),
277    paddingTop: getPadding(el, 'top'),
278    paddingRight: getPadding(el, 'right'),
279    paddingBottom: getPadding(el, 'bottom'),
280    paddingLeft: getPadding(el, 'left'),
281    borderTop: getBorder(el, 'top'),
282    borderRight: getBorder(el, 'right'),
283    borderBottom: getBorder(el, 'bottom'),
284    borderLeft: getBorder(el, 'left'),
285    marginTop: getMargin(el, 'top'),
286    marginRight: getMargin(el, 'right'),
287    marginBottom: getMargin(el, 'bottom'),
288    marginLeft: getMargin(el, 'left'),
289  }
290
291  // innerHeight: Get the current computed height for the first
292  // element in the set of matched elements, including padding but not border.
293
294  // outerHeight: Get the current computed height for the first
295  // element in the set of matched elements, including padding, border,
296  // and optionally margin. Returns a number (without 'px') representation
297  // of the value or null if called on an empty set of elements.
298
299  dimensions.heightWithPadding = el.innerHeight()
300  dimensions.heightWithBorder = el.innerHeight() + getTotalFor(['borderTop', 'borderBottom'], dimensions)
301  dimensions.heightWithMargin = el.outerHeight(true)
302
303  dimensions.widthWithPadding = el.innerWidth()
304  dimensions.widthWithBorder = el.innerWidth() + getTotalFor(['borderRight', 'borderLeft'], dimensions)
305  dimensions.widthWithMargin = el.outerWidth(true)
306
307  return dimensions
308}
309
310function getAttr (el, attr) {
311  // nuke anything thats not a number or a negative symbol
312  const num = _.toNumber(el.css(attr).replace(/[^0-9\.-]+/, ''))
313
314  if (!_.isFinite(num)) {
315    throw new Error('Element attr did not return a valid number')
316  }
317
318  return num
319}
320
321function getPadding (el, dir) {
322  return getAttr(el, `padding-${dir}`)
323}
324
325function getBorder (el, dir) {
326  return getAttr(el, `border-${dir}-width`)
327}
328
329function getMargin (el, dir) {
330  return getAttr(el, `margin-${dir}`)
331}
332
333function getTotalFor (directions, dimensions) {
334  return _.reduce(directions, (memo, direction) => memo + dimensions[direction], 0)
335}
336
337function getOuterSize (el) {
338  return {
339    width: el.outerWidth(true),
340    height: el.outerHeight(true),
341  }
342}
343
344function isInViewport (win, el) {
345  let rect = el.getBoundingClientRect()
346
347  return (
348    rect.top >= 0 &&
349    rect.left >= 0 &&
350    rect.bottom <= $(win).height() &&
351    rect.right <= $(win).width()
352  )
353}
354
355function scrollIntoView (win, el) {
356  if (!el || isInViewport(win, el)) return
357
358  el.scrollIntoView()
359}
360
361const sizzleRe = /sizzle/i
362
363function getElementsForSelector ({ root, selector, method, cypressDom }) {
364  let $el = null
365
366  try {
367    if (method === 'contains') {
368      $el = root.find(cypressDom.getContainsSelector(selector))
369      if ($el.length) {
370        $el = cypressDom.getFirstDeepestElement($el)
371      }
372    } else {
373      $el = root.find(selector)
374    }
375  } catch (err) {
376    // if not a sizzle error, ignore it and let $el be null
377    if (!sizzleRe.test(err.stack)) throw err
378  }
379
380  return $el
381}
382
383function addCssAnimationDisabler ($body) {
384  $(`
385    <style id="__cypress-animation-disabler">
386      *, *:before, *:after {
387        transition-property: none !important;
388        animation: none !important;
389      }
390    </style>
391  `).appendTo($body)
392}
393
394function removeCssAnimationDisabler ($body) {
395  $body.find('#__cypress-animation-disabler').remove()
396}
397
398function addBlackout ($body, selector) {
399  let $el
400  try {
401    $el = $body.find(selector)
402    if (!$el.length) return
403  } catch (err) {
404    // if it's an invalid selector, just ignore it
405    return
406  }
407
408  const dimensions = getElementDimensions($el)
409  const width = dimensions.widthWithBorder
410  const height = dimensions.heightWithBorder
411  const top = dimensions.offset.top
412  const left = dimensions.offset.left
413
414  const style = styles(`
415    ${resetStyles}
416    position: absolute;
417    top: ${top}px;
418    left: ${left}px;
419    width: ${width}px;
420    height: ${height}px;
421    background-color: black;
422    z-index: 2147483647;
423  `)
424
425  $(`<div class="__cypress-blackout" style="${style}">`).appendTo($body)
426}
427
428function removeBlackouts ($body) {
429  $body.find('.__cypress-blackout').remove()
430}
431
432export default {
433  addBlackout,
434  removeBlackouts,
435  addElementBoxModelLayers,
436  addHitBoxLayer,
437  addOrUpdateSelectorPlaygroundHighlight,
438  addCssAnimationDisabler,
439  removeCssAnimationDisabler,
440  getElementsForSelector,
441  getOuterSize,
442  scrollIntoView,
443}
444
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)