Best JavaScript code snippet using cypress
dom.js
Source:dom.js
1import _ from 'lodash'2import { $ } from '@packages/driver'3import Promise from 'bluebird'4import selectorPlaygroundHighlight from '../selector-playground/highlight'5const styles = (styleString) => {6 return styleString.replace(/\s*\n\s*/g, '')7}8const resetStyles = `9 border: none !important;10 margin: 0 !important;11 padding: 0 !important;12`13function addHitBoxLayer (coords, body) {14 if (body == null) {15 body = $('body')16 }17 const height = 1018 const width = 1019 const dotHeight = 420 const dotWidth = 421 const top = coords.y - height / 222 const left = coords.x - width / 223 const dotTop = height / 2 - dotHeight / 224 const dotLeft = width / 2 - dotWidth / 225 const boxStyles = styles(`26 ${resetStyles}27 position: absolute;28 top: ${top}px;29 left: ${left}px;30 width: ${width}px;31 height: ${height}px;32 background-color: red;33 border-radius: 5px;34 box-shadow: 0 0 5px #333;35 z-index: 2147483647;36 `)37 const box = $(`<div class="__cypress-highlight" style="${boxStyles}" />`)38 const wrapper = $(`<div style="${styles(resetStyles)} position: relative" />`).appendTo(box)39 const dotStyles = styles(`40 ${resetStyles}41 position: absolute;42 top: ${dotTop}px;43 left: ${dotLeft}px;44 height: ${dotHeight}px;45 width: ${dotWidth}px;46 height: ${dotHeight}px;47 background-color: pink;48 border-radius: 5px;49 `)50 $(`<div style="${dotStyles}">`).appendTo(wrapper)51 return box.appendTo(body)52}53function addElementBoxModelLayers ($el, body) {54 if (body == null) {55 body = $('body')56 }57 const dimensions = getElementDimensions($el)58 const container = $('<div class="__cypress-highlight">')59 const layers = {60 Content: '#9FC4E7',61 Padding: '#C1CD89',62 Border: '#FCDB9A',63 Margin: '#F9CC9D',64 }65 // create the margin / bottom / padding layers66 _.each(layers, (color, attr) => {67 let obj68 switch (attr) {69 case 'Content':70 // rearrange the contents offset so71 // its inside of our border + padding72 obj = {73 width: dimensions.width,74 height: dimensions.height,75 top: dimensions.offset.top + dimensions.borderTop + dimensions.paddingTop,76 left: dimensions.offset.left + dimensions.borderLeft + dimensions.paddingLeft,77 }78 break79 default:80 obj = {81 width: getDimensionsFor(dimensions, attr, 'width'),82 height: getDimensionsFor(dimensions, attr, 'height'),83 top: dimensions.offset.top,84 left: dimensions.offset.left,85 }86 }87 // if attr is margin then we need to additional88 // subtract what the actual marginTop + marginLeft89 // values are, since offset disregards margin completely90 if (attr === 'Margin') {91 obj.top -= dimensions.marginTop92 obj.left -= dimensions.marginLeft93 }94 // bail if the dimensions of this layer match the previous one95 // so we dont create unnecessary layers96 if (dimensionsMatchPreviousLayer(obj, container)) return97 return createLayer($el, attr, color, container, obj)98 })99 container.appendTo(body)100 container.children().each((index, el) => {101 const $el = $(el)102 const top = $el.data('top')103 const left = $el.data('left')104 // dont ask... for some reason we105 // have to run offset twice!106 _.times(2, () => $el.offset({ top, left }))107 })108 return container109}110function getOrCreateSelectorHelperDom ($body) {111 let $container = $body.find('.__cypress-selector-playground')112 if ($container.length) {113 const shadowRoot = $container.find('.__cypress-selector-playground-shadow-root-container')[0].shadowRoot114 return Promise.resolve({115 $container,116 shadowRoot,117 $reactContainer: $(shadowRoot).find('.react-container'),118 $cover: $container.find('.__cypress-selector-playground-cover'),119 })120 }121 $container = $('<div />')122 .addClass('__cypress-selector-playground')123 .css({ position: 'static' })124 .appendTo($body)125 const $shadowRootContainer = $('<div />')126 .addClass('__cypress-selector-playground-shadow-root-container')127 .css({ position: 'static' })128 .appendTo($container)129 const shadowRoot = $shadowRootContainer[0].attachShadow({ mode: 'open' })130 const $reactContainer = $('<div />')131 .addClass('react-container')132 .appendTo(shadowRoot)133 const $cover = $('<div />')134 .addClass('__cypress-selector-playground-cover')135 .appendTo($container)136 return Promise.try(() => fetch('/__cypress/runner/cypress_selector_playground.css'))137 .then((result) => {138 return result.text()139 })140 .then((content) => {141 $('<style />', { html: content }).prependTo(shadowRoot)142 return { $container, shadowRoot, $reactContainer, $cover }143 })144 .catch((error) => {145 console.error('Selector playground failed to load styles:', error) // eslint-disable-line no-console146 return { $container, shadowRoot, $reactContainer, $cover }147 })148}149function addOrUpdateSelectorPlaygroundHighlight ({ $el, $body, selector, showTooltip, onClick }) {150 getOrCreateSelectorHelperDom($body)151 .then(({ $container, shadowRoot, $reactContainer, $cover }) => {152 if (!$el) {153 selectorPlaygroundHighlight.unmount($reactContainer[0])154 $cover.off('click')155 $container.remove()156 return157 }158 const borderSize = 2159 const styles = $el.map((__, el) => {160 const $el = $(el)161 const offset = $el.offset()162 return {163 position: 'absolute',164 margin: 0,165 padding: 0,166 width: $el.outerWidth(),167 height: $el.outerHeight(),168 top: offset.top - borderSize,169 left: offset.left - borderSize,170 transform: $el.css('transform'),171 zIndex: getZIndex($el),172 }173 }).get()174 if (styles.length === 1) {175 $cover176 .css(styles[0])177 .off('click')178 .on('click', onClick)179 }180 selectorPlaygroundHighlight.render($reactContainer[0], {181 selector,182 appendTo: shadowRoot,183 boundary: $body[0],184 showTooltip,185 styles,186 })187 })188}189function createLayer ($el, attr, color, container, dimensions) {190 const transform = $el.css('transform')191 const css = {192 transform,193 width: dimensions.width,194 height: dimensions.height,195 position: 'absolute',196 zIndex: getZIndex($el),197 backgroundColor: color,198 opacity: 0.6,199 }200 return $('<div>')201 .css(css)202 .attr('data-top', dimensions.top)203 .attr('data-left', dimensions.left)204 .attr('data-layer', attr)205 .prependTo(container)206}207function dimensionsMatchPreviousLayer (obj, container) {208 // since we're prepending to the container that209 // means the previous layer is actually the first child element210 const previousLayer = container.children().first()211 // bail if there is no previous layer212 if (!previousLayer.length) { return }213 return obj.width === previousLayer.width() &&214 obj.height === previousLayer.height()215}216function getDimensionsFor (dimensions, attr, dimension) {217 return dimensions[`${dimension}With${attr}`]218}219function getZIndex (el) {220 if (/^(auto|0)$/.test(el.css('zIndex'))) {221 return 2147483647222 } else {223 return _.toNumber(el.css('zIndex'))224 }225}226function getElementDimensions (el) {227 const dimensions = {228 offset: el.offset(), // offset disregards margin but takes into account border + padding229 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 set230 width: el.width(),231 paddingTop: getPadding(el, 'top'),232 paddingRight: getPadding(el, 'right'),233 paddingBottom: getPadding(el, 'bottom'),234 paddingLeft: getPadding(el, 'left'),235 borderTop: getBorder(el, 'top'),236 borderRight: getBorder(el, 'right'),237 borderBottom: getBorder(el, 'bottom'),238 borderLeft: getBorder(el, 'left'),239 marginTop: getMargin(el, 'top'),240 marginRight: getMargin(el, 'right'),241 marginBottom: getMargin(el, 'bottom'),242 marginLeft: getMargin(el, 'left'),243 }244 // innerHeight: Get the current computed height for the first245 // element in the set of matched elements, including padding but not border.246 // outerHeight: Get the current computed height for the first247 // element in the set of matched elements, including padding, border,248 // and optionally margin. Returns a number (without 'px') representation249 // of the value or null if called on an empty set of elements.250 dimensions.heightWithPadding = el.innerHeight()251 dimensions.heightWithBorder = el.innerHeight() + getTotalFor(['borderTop', 'borderBottom'], dimensions)252 dimensions.heightWithMargin = el.outerHeight(true)253 dimensions.widthWithPadding = el.innerWidth()254 dimensions.widthWithBorder = el.innerWidth() + getTotalFor(['borderRight', 'borderLeft'], dimensions)255 dimensions.widthWithMargin = el.outerWidth(true)256 return dimensions257}258function getAttr (el, attr) {259 // nuke anything thats not a number or a negative symbol260 const num = _.toNumber(el.css(attr).replace(/[^0-9\.-]+/, ''))261 if (!_.isFinite(num)) {262 throw new Error('Element attr did not return a valid number')263 }264 return num265}266function getPadding (el, dir) {267 return getAttr(el, `padding-${dir}`)268}269function getBorder (el, dir) {270 return getAttr(el, `border-${dir}-width`)271}272function getMargin (el, dir) {273 return getAttr(el, `margin-${dir}`)274}275function getTotalFor (directions, dimensions) {276 return _.reduce(directions, (memo, direction) => memo + dimensions[direction], 0)277}278function getOuterSize (el) {279 return {280 width: el.outerWidth(true),281 height: el.outerHeight(true),282 }283}284function isInViewport (win, el) {285 let rect = el.getBoundingClientRect()286 return (287 rect.top >= 0 &&288 rect.left >= 0 &&289 rect.bottom <= $(win).height() &&290 rect.right <= $(win).width()291 )292}293function scrollIntoView (win, el) {294 if (!el || isInViewport(win, el)) return295 el.scrollIntoView()296}297const sizzleRe = /sizzle/i298function getElementsForSelector ({ root, selector, method, cypressDom }) {299 let $el = null300 try {301 if (method === 'contains') {302 $el = root.find(cypressDom.getContainsSelector(selector))303 if ($el.length) {304 $el = cypressDom.getFirstDeepestElement($el)305 }306 } else {307 $el = root.find(selector)308 }309 } catch (err) {310 // if not a sizzle error, ignore it and let $el be null311 if (!sizzleRe.test(err.stack)) throw err312 }313 return $el314}315function addCssAnimationDisabler ($body) {316 $(`317 <style id="__cypress-animation-disabler">318 *, *:before, *:after {319 transition-property: none !important;320 animation: none !important;321 }322 </style>323 `).appendTo($body)324}325function removeCssAnimationDisabler ($body) {326 $body.find('#__cypress-animation-disabler').remove()327}328function addBlackout ($body, selector) {329 let $el330 try {331 $el = $body.find(selector)332 if (!$el.length) return333 } catch (err) {334 // if it's an invalid selector, just ignore it335 return336 }337 const dimensions = getElementDimensions($el)338 const width = dimensions.widthWithBorder339 const height = dimensions.heightWithBorder340 const top = dimensions.offset.top341 const left = dimensions.offset.left342 const style = styles(`343 ${resetStyles}344 position: absolute;345 top: ${top}px;346 left: ${left}px;347 width: ${width}px;348 height: ${height}px;349 background-color: black;350 z-index: 2147483647;351 `)352 $(`<div class="__cypress-blackout" style="${style}">`).appendTo($body)353}354function removeBlackouts ($body) {355 $body.find('.__cypress-blackout').remove()356}357export default {358 addBlackout,359 removeBlackouts,360 addElementBoxModelLayers,361 addHitBoxLayer,362 addOrUpdateSelectorPlaygroundHighlight,363 addCssAnimationDisabler,364 removeCssAnimationDisabler,365 getElementsForSelector,366 getOuterSize,367 scrollIntoView,...
aut-iframe.js
Source:aut-iframe.js
...298 afterScreenshot = (config) => {299 // could fail if iframe is cross-origin, so fail gracefully300 try {301 if (config.disableTimersAndAnimations) {302 dom.removeCssAnimationDisabler(this._body())303 }304 dom.removeBlackouts(this._body())305 } catch (err) {306 /* eslint-disable no-console */307 console.error('Failed to modify app dom:')308 console.error(err)309 /* eslint-disable no-console */310 }311 }...
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.removeCssAnimationDisabler()4 })5})6MIT © [Saurabh Kumar](
Using AI Code Generation
1describe('Test', () => {2 it('should work', () => {3 cy.get('.home-list > :nth-child(1) > a').click()4 cy.get('.animation').should('be.visible')5 cy.get('.animation').should('have.css', 'opacity', '1')6 cy.get('.animation').should('have.css', 'transform', 'matrix(1, 0, 0, 1, 0, 0)')7 cy.get('.animation').should('have.css', 'transition', 'opacity 1s ease 0s, transform 1s ease 0s')8 cy.removeCssAnimationDisabler()9 cy.get('.animation').should('be.visible')10 cy.get('.animation').should('have.css', 'opacity', '0')11 cy.get('.animation').should('have.css', 'transform', 'matrix(1, 0, 0, 1, -100, 0)')12 cy.get('.animation').should('have.css', 'transition', 'opacity 1s ease 0s, transform 1s ease 0s')13 })14})
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!