Best JavaScript code snippet using cypress
we-retail-instore.js
Source:we-retail-instore.js  
...74        .addTestCase(new hobs.TestCase('Switch catalog', {demoMode: DEBUG})75            // Check the initial catalog is visible76            .asserts.isVisible([selectors.catalog.cover.view,77                selectors.catalog.cover.background + selectors.catalog.cover.demo].join(' '))78            .asserts.isInViewport([selectors.catalog.cover.view,79                selectors.catalog.cover.background + selectors.catalog.cover.demo].join(' '))80            .execSyncFct(function() {81                cache.currentCatalog = hobs.find(selectors.catalog.cover.view + ':last');82                cache.initialCatalog = cache.currentCatalog;83                cache.previousCatalog = cache.currentCatalog;84            })85            // Swipe to another catalog86            .sistine.swipeUp(selectors.catalog.cover.view + ':last')87            .asserts.isInViewport([selectors.catalog.cover.view,88                selectors.catalog.cover.background + selectors.catalog.cover.demo].join(' '), false)89            .asserts.isVisible(selectors.catalog.cover.view)90            .asserts.isInViewport(selectors.catalog.cover.view + ':last')91            .asserts.isTrue(function() {92                cache.currentCatalog = hobs.find(selectors.catalog.cover.view + ':last');93                return cache.previousCatalog.get(0) !== cache.currentCatalog.get(0);94            })95            .execSyncFct(function() {96                cache.previousCatalog = cache.currentCatalog;97            })98            // Swipe back to the initial catalog99            .sistine.swipeDown(selectors.catalog.cover.view + ':last')100            .asserts.isVisible(selectors.catalog.cover.view + ':first')101            .asserts.isInViewport([selectors.catalog.cover.view,102                selectors.catalog.cover.background + ':not(' + selectors.catalog.cover.demo + ')'].join(' '), false)103            .asserts.isVisible([selectors.catalog.cover.view,104                selectors.catalog.cover.background + selectors.catalog.cover.demo].join(' '))105            .asserts.isInViewport([selectors.catalog.cover.view,106                selectors.catalog.cover.background + selectors.catalog.cover.demo].join(' '))107            .asserts.isTrue(function() {108                cache.currentCatalog = hobs.find(selectors.catalog.cover.view + ':last');109                return cache.previousCatalog.get(0) !== cache.currentCatalog.get(0)110                    && cache.currentCatalog.get(0) === cache.initialCatalog.get(0);111            })112        )113        // It should be possible to toggle the callouts when tapping the buttons114        .addTestCase(new hobs.TestCase('Toggle product callouts', {demoMode: DEBUG})115            // There should be buttons and callouts on the current catalog, and the callouts should be hidden116            .asserts.exists([selectors.catalog.current, selectors.product.callout.view].join(' '))117            .asserts.exists([selectors.catalog.current, selectors.product.callout.button].join(' '))118            .asserts.isVisible(selectors.product.callout.view, false)119            .asserts.isTrue(function() {120                return hobs.find(selectors.product.callout.view).length >= 2;121            })122            // Tapping a callout should show it123            .sistine.tap(selectors.product.callout.button + ':eq(0)')124            .asserts.isVisible(selectors.product.callout.view + ':eq(0)')125            // Tapping it again should close it126            .sistine.tap(selectors.product.callout.button + ':eq(0)')127            .asserts.isVisible(selectors.product.callout.view + ':eq(0)', false)128            // Tapping a second callout when one is already open should close it129            .sistine.tap(selectors.product.callout.button + ':eq(0)')130            .asserts.isVisible(selectors.product.callout.view + ':eq(0)')131            .sistine.tap(selectors.product.callout.button + ':eq(1)')132            .asserts.isVisible(selectors.product.callout.view + ':eq(0)', false)133            .asserts.isVisible(selectors.product.callout.view + ':eq(1)')134            .sistine.tap(selectors.product.callout.button + ':eq(1)')135            .asserts.isVisible(selectors.product.callout.view + ':eq(1)', false)136        )137        // Position on the right category for the rest of the test cases138        .addTestCase(new hobs.TestCase('Select a specific product category', {demoMode: DEBUG})139            // Position on the right category140            .asserts.exists([selectors.catalog.current, selectors.catalog.cover.view].join(' '))141            .sistine.swipeLeft([selectors.catalog.current, selectors.catalog.cover.view].join(' '))142            .asserts.isInViewport([selectors.catalog.current, selectors.catalog.cover.view].join(' '), false)143            .asserts.isVisible([selectors.catalog.current, selectors.category.view].join(' ') + ':lt(2)')144            .asserts.isInViewport([selectors.catalog.current, selectors.category.view].join(' ') + ':lt(2)')145            .sistine.swipeLeft([selectors.catalog.current, selectors.catalog.cover.view].join(' '))146            .asserts.isVisible([selectors.catalog.current, selectors.category.view].join(' ') + ':gt(0):lt(2)')147            .asserts.isInViewport([selectors.catalog.current, selectors.category.view].join(' ') + ':gt(0):lt(2)')148            .sistine.swipeLeft([selectors.catalog.current, selectors.catalog.cover.view].join(' '))149            .asserts.isVisible([selectors.catalog.current, selectors.category.view].join(' ') + ':gt(1):lt(3)')150            .asserts.isInViewport([selectors.catalog.current, selectors.category.view].join(' ') + ':gt(1):lt(2)')151            .asserts.exists([selectors.catalog.current, selectors.category.view].join(' ') + ':eq(3) ' +152                selectors.product.demo)153        )154        // It should be possible to swipe up and down between products155        .addTestCase(new hobs.TestCase('Switch product', {demoMode: DEBUG})156            // Check initial product is visible157            .asserts.isVisible(158                [selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '))159            .asserts.isInViewport(160                [selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '))161            .execSyncFct(function() {162                cache.currentProduct = hobs.find([selectors.catalog.current, selectors.category.view + ':eq(3)',163                    selectors.product.current].join(' '));164                cache.initialProduct = cache.currentProduct;165                cache.previousProduct = cache.currentProduct;166            })167            // Swipe to another product168            .sistine.swipeUp([selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '))169            .asserts.isTrue(function() {170                cache.currentProduct = hobs.find([selectors.catalog.current, selectors.category.view + ':eq(3)',171                    selectors.product.current].join(' '));172                return cache.previousProduct.get(0) !== cache.currentProduct.get(0);173            })174            .execSyncFct(function() {175                cache.previousProduct = cache.currentProduct;176            })177            .asserts.isInViewport(178                [selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '), false)179            // Sipw back to the initial product180            .sistine.swipeDown([selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '))181            .asserts.isInViewport(182                [selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '))183            .asserts.isTrue(function() {184                cache.currentProduct = hobs.find([selectors.catalog.current, selectors.category.view + ':eq(3)',185                    selectors.product.current].join(' '));186                return cache.previousProduct.get(0) !== cache.currentProduct.get(0)187                    && cache.currentProduct.get(0) === cache.initialProduct.get(0);188            })189        )190        // Double-tapping should toggle the fullscreen view for the product191        .addTestCase(new hobs.TestCase('Open fullscreen product', {demoMode: DEBUG})192            // Open the product fullscreen view193            .asserts.isVisible(194                [selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '))195            .asserts.isInViewport(196                [selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '))197            .sistine.doubletap([selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '))198            .asserts.exists(selectors.product.fullscreen.view)199            .asserts.exists(selectors.product.fullscreen.bigThumbnail)200            .asserts.exists(selectors.product.fullscreen.smallThumbnail)201            .asserts.exists(selectors.product.fullscreen.description)202            .asserts.exists(selectors.product.fullscreen.button)203            .asserts.isVisible(selectors.product.fullscreen.view)204            // The selected product in the fullscreen view is the right one205            .asserts.isVisible(selectors.product.fullscreen.smallThumbnail)206            .asserts.isInViewport(selectors.product.fullscreen.smallThumbnail + selectors.product.demo)207            .asserts.hasCssClass(selectors.product.fullscreen.smallThumbnail + selectors.product.demo, 'active')208            .asserts.isVisible(selectors.product.fullscreen.bigThumbnail)209            .asserts.isInViewport(selectors.product.fullscreen.bigThumbnail + selectors.product.demo)210        )211        // Tapping one of the small thumbnails should change the product in the view212        .addTestCase(new hobs.TestCase('Change product', {demoMode: DEBUG})213            .asserts.exists(selectors.product.fullscreen.smallThumbnail + ':eq(1)')214            .sistine.tap(selectors.product.fullscreen.smallThumbnail + ':eq(1)')215            .asserts.hasCssClass(selectors.product.fullscreen.smallThumbnail + ':eq(0)', 'active', false)216            .asserts.hasCssClass(selectors.product.fullscreen.smallThumbnail + ':eq(1)', 'active')217            .asserts.isTrue(function() {218                var $smallThumbnails = hobs.find(selectors.product.fullscreen.smallThumbnail);219                var $bigThumbnail = hobs.find(selectors.product.fullscreen.bigThumbnail);220                return $smallThumbnails.eq(1).attr('data-path') === $bigThumbnail.attr('data-path');221            })222            .wait(300)223        )224        // Tapping the menu icon should toggle the product details225        .addTestCase(new hobs.TestCase('Toggle product details', {demoMode: DEBUG})226            // The description panel should be hidden by default227            .asserts.isVisible(selectors.product.fullscreen.button)228            .asserts.isInViewport(selectors.product.fullscreen.button)229            .asserts.isVisible(selectors.product.fullscreen.description)230            .asserts.isInViewport(selectors.product.fullscreen.description, false)231            // Tapping the menu icon should show the description panel232            .sistine.tap(selectors.product.fullscreen.button)233            .asserts.isVisible(selectors.product.fullscreen.button)234            .asserts.isInViewport(selectors.product.fullscreen.button)235            .asserts.isVisible(selectors.product.fullscreen.description)236            .asserts.isInViewport(selectors.product.fullscreen.description)237            // Tapping the menu icon again should show hide description panel238            .sistine.tap(selectors.product.fullscreen.button)239            .asserts.isVisible(selectors.product.fullscreen.button)240            .asserts.isInViewport(selectors.product.fullscreen.button)241            .asserts.isInViewport(selectors.product.fullscreen.description, false)242        )243        // Double-tapping the big thumbnail should close the fullscreen view244        .addTestCase(new hobs.TestCase('Close category', {demoMode: DEBUG})245            .asserts.isVisible(selectors.product.fullscreen.view)246            .asserts.isInViewport(selectors.product.fullscreen.view)247            .sistine.doubletap(selectors.product.fullscreen.bigThumbnail)248            .asserts.isVisible(selectors.product.fullscreen.view, false)249            .asserts.isInViewport(selectors.product.fullscreen.view, false)250            // The visible product should now match the one that was selected in the fullscreen view251            .asserts.isInViewport(252                [selectors.product.view, selectors.product.thumbnail + selectors.product.demo].join(' '), false)253        )254        // Swiping right should bring you back to the catalog cover255        .addTestCase(new hobs.TestCase('Switch to catalog cover', {demoMode: DEBUG})256            .asserts.isInViewport([selectors.catalog.current, selectors.catalog.cover.view].join(' '), false)257            .asserts.isVisible([selectors.catalog.current, selectors.category.view + ':gt(1):lt(3)'].join(' '))258            .asserts.isInViewport([selectors.catalog.current, selectors.category.view + ':gt(1):lt(2)'].join(' '))259            .sistine.swipeRight([selectors.catalog.current, selectors.category.view].join(' '))260            .asserts.isVisible([selectors.catalog.current, selectors.category.view + ':gt(0):lt(2)'].join(' '))261            .asserts.isInViewport([selectors.catalog.current, selectors.category.view + ':gt(0):lt(2)'].join(' '))262            .sistine.swipeRight([selectors.catalog.current, selectors.category.view].join(' '))263            .asserts.isVisible([selectors.catalog.current, selectors.category.view + ':lt(2)'].join(' '))264            .asserts.isInViewport([selectors.catalog.current, selectors.category.view + ':lt(2)'].join(' '))265            .sistine.swipeRight([selectors.catalog.current, selectors.category.view].join(' '))266            .asserts.isInViewport([selectors.catalog.current, selectors.category.view].join(' '), false)267            .asserts.isInViewport([selectors.catalog.current, selectors.catalog.cover.view].join(' '))268        )269        ;...ConsultationCareAndConcealerRecommendation.spec.js
Source:ConsultationCareAndConcealerRecommendation.spec.js  
1/**2 * @prettier3 */4import React from 'react';5import {expect} from 'chai';6import {shallow} from 'enzyme';7import {ConsultationCareAndConcealerRecommendation} from '../../src/js/components/react/ConsultationCareAndConcealerRecommendation';8import {careProducts} from '../stubs/consultation-products';9describe('Component: <ConsultationCareAndConcealerRecommendation />', () => {10    it('renders a title for the collection', () => {11        const reason = 'Foo bar baz';12        const handleClick = () => {};13        const isInViewport = false;14        const stopWatcher = () => {};15        const title = 'Foo bar';16        const wrapper = shallow(17            <ConsultationCareAndConcealerRecommendation18                handleClick={handleClick}19                isInViewport={isInViewport}20                reason={reason}21                products={careProducts}22                stopWatcher={stopWatcher}23                title={title}24            />25        );26        const actual = wrapper.find('.qa-title').text();27        const expected = title;28        expect(actual).to.equal(expected);29    });30    it('renders a subtitle for the collection', () => {31        const reason = 'Foo bar baz';32        const handleClick = () => {};33        const isInViewport = false;34        const stopWatcher = () => {};35        const subtitle = 'Foo bar baz';36        const title = 'Foo bar';37        const wrapper = shallow(38            <ConsultationCareAndConcealerRecommendation39                handleClick={handleClick}40                isInViewport={isInViewport}41                reason={reason}42                products={careProducts}43                stopWatcher={stopWatcher}44                subtitle={subtitle}45                title={title}46            />47        );48        const actual = wrapper.find('.qa-subtitle').text();49        const expected = subtitle;50        expect(actual).to.equal(expected);51    });52    it('renders a reason for the recommendation', () => {53        const reason = 'Foo bar baz';54        const handleClick = () => {};55        const isInViewport = false;56        const stopWatcher = () => {};57        const title = 'Foo bar';58        const wrapper = shallow(59            <ConsultationCareAndConcealerRecommendation60                handleClick={handleClick}61                isInViewport={isInViewport}62                reason={reason}63                products={careProducts}64                stopWatcher={stopWatcher}65                title={title}66            />67        );68        const actual = wrapper.find('.qa-reason').text();69        const expected = reason;70        expect(actual).to.equal(expected);71    });72    it('renders each product in a grid', () => {73        const reason = 'Foo bar baz';74        const handleClick = () => {};75        const isInViewport = false;76        const stopWatcher = () => {};77        const title = 'Foo bar';78        const wrapper = shallow(79            <ConsultationCareAndConcealerRecommendation80                handleClick={handleClick}81                isInViewport={isInViewport}82                reason={reason}83                products={careProducts}84                stopWatcher={stopWatcher}85                title={title}86            />87        );88        const actual = wrapper.find('.o-layout__item').length;89        const expected = careProducts.length;90        expect(actual).to.equal(expected);91    });92    it("renders the product's title", () => {93        const reason = 'Foo bar baz';94        const handleClick = () => {};95        const isInViewport = false;96        const stopWatcher = () => {};97        const title = 'Foo bar';98        const wrapper = shallow(99            <ConsultationCareAndConcealerRecommendation100                handleClick={handleClick}101                isInViewport={isInViewport}102                reason={reason}103                products={careProducts}104                stopWatcher={stopWatcher}105                title={title}106            />107        );108        const actual = wrapper109            .find('.o-layout__item')110            .first()111            .find('.qa-heading2')112            .text();113        const expected = careProducts[0].title;114        expect(actual).to.equal(expected);115    });116    it("renders a product's price", () => {117        const reason = 'Foo bar baz';118        const handleClick = () => {};119        const isInViewport = false;120        const stopWatcher = () => {};121        const title = 'Foo bar';122        const wrapper = shallow(123            <ConsultationCareAndConcealerRecommendation124                handleClick={handleClick}125                isInViewport={isInViewport}126                reason={reason}127                products={careProducts}128                stopWatcher={stopWatcher}129                title={title}130            />131        );132        const actual = wrapper133            .find('.o-layout__item')134            .first()135            .find('.qa-price')136            .text();137        const expected = '£5';138        expect(actual).to.equal(expected);139    });140    it("renders a product's Add to Cart button with the product's variant id", () => {141        const reason = 'Foo bar baz';142        const handleClick = () => {};143        const isInViewport = false;144        const stopWatcher = () => {};145        const title = 'Foo bar';146        const wrapper = shallow(147            <ConsultationCareAndConcealerRecommendation148                handleClick={handleClick}149                isInViewport={isInViewport}150                reason={reason}151                products={careProducts}152                stopWatcher={stopWatcher}153                title={title}154            />155        );156        const actual = wrapper157            .find('.o-layout__item')158            .first()159            .find('AddToCartButton')160            .prop('variantId');161        const expected = careProducts[0].variantId;162        expect(actual).to.equal(expected);163    });164    it('renders no image for the product if it is not in the viewport', () => {165        const reason = 'Foo bar baz';166        const handleClick = () => {};167        const isInViewport = false;168        const stopWatcher = () => {};169        const title = 'Foo bar';170        const wrapper = shallow(171            <ConsultationCareAndConcealerRecommendation172                handleClick={handleClick}173                isInViewport={isInViewport}174                reason={reason}175                products={careProducts}176                stopWatcher={stopWatcher}177                title={title}178            />179        );180        const actual = wrapper181            .find('.o-layout__item')182            .first()183            .find('.qa-image')184            .prop('style').backgroundImage;185        const expected = null;186        expect(actual).to.equal(expected);187    });188    it('renders the box image for the product if it is in the viewport', () => {189        const reason = 'Foo bar baz';190        const handleClick = () => {};191        const isInViewport = true;192        const stopWatcher = () => {};193        const title = 'Foo bar';194        const wrapper = shallow(195            <ConsultationCareAndConcealerRecommendation196                handleClick={handleClick}197                isInViewport={isInViewport}198                reason={reason}199                products={careProducts}200                stopWatcher={stopWatcher}201                title={title}202            />203        );204        const actual = wrapper205            .find('.o-layout__item')206            .first()207            .find('.qa-image')208            .prop('style').backgroundImage;209        const expected = `url(${careProducts[0].image})`;210        expect(actual).to.equal(expected);211    });212    it('renders the details URL for the product', () => {213        const reason = 'Foo bar baz';214        const handleClick = () => {};215        const isInViewport = false;216        const stopWatcher = () => {};217        const title = 'Foo bar';218        const wrapper = shallow(219            <ConsultationCareAndConcealerRecommendation220                handleClick={handleClick}221                isInViewport={isInViewport}222                reason={reason}223                products={careProducts}224                stopWatcher={stopWatcher}225                title={title}226            />227        );228        const actual = wrapper229            .find('.o-layout__item')230            .first()231            .find('.qa-url')232            .prop('href');233        const expected = `/products/${careProducts[0].key}`;234        expect(actual).to.equal(expected);235    });...is-in-viewport.js
Source:is-in-viewport.js  
...12// expose isInViewport as a custom pseudo-selector13$.extend($.expr[':'], {14  // if $.expr.createPseudo is available, use it15  'in-viewport': $.expr.createPseudo16    ? $.expr.createPseudo(function (argsString) { return function (currElement) { return isInViewport(currElement, getSelectorArgs(argsString)); }; })17  : function (currObj, index, meta) { return isInViewport(currObj, getSelectorArgs(meta[3])); }18});19// expose isInViewport as a function too20// this lets folks pass around actual objects as options (like custom viewport)21// and doesn't tie 'em down to strings. It also prevents isInViewport from22// having to look up and wrap the dom element corresponding to the viewport selector23$.fn.isInViewport = function(options) {24  return this.filter(function (i, el) { return isInViewport(el, options); })25};26$.fn.run = run;27// lets you chain any arbitrary function or an array of functions and returns a jquery object28function run(args) {29  var this$1 = this;30  if (arguments.length === 1 && typeof args === 'function') {31    args = [args];32  }33  if (!(args instanceof Array)) {34    throw new SyntaxError('isInViewport: Argument(s) passed to .do/.run should be a function or an array of functions')35  }36  args.forEach(function (arg) {37    if (typeof arg !== 'function') {38      console.warn('isInViewport: Argument(s) passed to .do/.run should be a function or an array of functions');39      console.warn('isInViewport: Ignoring non-function values in array and moving on');40    } else {41      [].slice.call(this$1).forEach(function (t) { return arg.call($(t)); });42    }43  });44  return this45}46// gets the width of the scrollbar47function getScrollbarWidth(viewport) {48  // append a div that has 100% width to get true width of viewport49  var el = $('<div></div>').css({50    width: '100%'51  });52  viewport.append(el);53  // subtract true width from the viewport width which is inclusive54  // of scrollbar by default55  var scrollBarWidth = viewport.width() - el.width();56  // remove our element from DOM57  el.remove();58  return scrollBarWidth59}60// Returns true if DOM element `element` is in viewport61function isInViewport(element, options) {62  var ref = element.getBoundingClientRect();63  var top = ref.top;64  var bottom = ref.bottom;65  var left = ref.left;66  var right = ref.right;67  var settings = $.extend({68    tolerance: 0,69    viewport: window70  }, options);71  var isVisibleFlag = false;72  var $viewport = settings.viewport.jquery ? settings.viewport : $(settings.viewport);73  if (!$viewport.length) {74    console.warn('isInViewport: The viewport selector you have provided matches no element on page.');75    console.warn('isInViewport: Defaulting to viewport as window');...scrollupbar.js
Source:scrollupbar.js  
...12    }, options);13    function isFullyInViewport() {14      return $window.scrollTop() <= $bar.offset().top;15    }16    function isInViewport() {17      return $window.scrollTop() < $bar.offset().top + $bar.outerHeight();18    }19    var $window = $(window),20        $document = $(document),21        minY = $bar.css('position') == 'fixed' ? 0 : $bar.offset().top,22        lastY = $window.scrollTop(), // Use last Y to detect scroll direction.23        initialPosTop = $bar.position().top,24        iOS = /(iPad|iPhone|iPod)/g.test(navigator.userAgent),25        timeout;26    $.scrollupbar.isInViewport = isInViewport();27    $.scrollupbar.isFullyInViewport = isFullyInViewport();28    // iOS can't handle momentum scroll properly (See discussion on29    // http://stackoverflow.com/questions/2863547).30    if (!iOS) {31      $window.on('scroll.scrollupbar', function() {32        var y = $window.scrollTop(),33            barHeight = $bar.outerHeight();34        // Ignore elastic scrolling.35        if (y < 0 || y > ($document.height() - $window.height())) {36          return;37        }38        // Cancel the event fired by the previous scroll.39        if (timeout) {40          clearTimeout(timeout);41        }42        if (y < lastY) { // Scrolling up43          // If the bar is hidden, place it right above the top frame.44          if (!$.scrollupbar.isInViewport && lastY - barHeight >= minY) {45            $bar.css('top', lastY - barHeight);46            $.scrollupbar.isInViewport = true;47            options.enterViewport();48          }49          // Scrolls up bigger than the bar's height fixes the bar on top.50          if (isFullyInViewport()) {51            if (y >= minY) {52              $bar.css({53                'position': 'fixed',54                'top': 0,             55              });56            } else {57              $bar.css({58                'position': 'absolute',59                'top': initialPosTop60              });61            }62            if (!$.scrollupbar.isFullyInViewport) {63              $.scrollupbar.isFullyInViewport = true;64              options.fullyEnterViewport();65            }66          }67          // Fire an event to reveal the entire bar after 400ms if the scroll68          // wasn't big enough.69          timeout = setTimeout(function() {70            if (!isFullyInViewport()) {71              $bar.css({72                'position': 'fixed',73                'top': $bar.offset().top - y74              });75              $bar.animate({'top': 0}, 100, function() {76                $.scrollupbar.isFullyInViewport = true;77                options.fullyEnterViewport();78              });79            }80          }, 400);81        } else if (y > lastY) { // Scrolling down82          // Unfix the bar allowing it to scroll with the page.83          if ($.scrollupbar.isFullyInViewport) {84            $bar.css({85              'position': 'absolute',86              'top': lastY > minY ? lastY : initialPosTop87            });88            if (!isFullyInViewport()) {89              $.scrollupbar.isFullyInViewport = false;90              options.partiallyExitViewport();91            }92          }93          if ($.scrollupbar.isInViewport && !isInViewport()) {94            $.scrollupbar.isInViewport = false;95            options.exitViewport();96          }97          // Fire an event to hide the entire bar after 400ms if the scroll98          // wasn't big enough.99          timeout = setTimeout(function() {100            if (isInViewport() && y - barHeight >= minY) {101              $bar.animate({'top': y - barHeight}, 100, function() {102                $.scrollupbar.isInViewport = false;103                options.exitViewport();104              });105            }106          }, 400);107        }108        lastY = y;109      });110    } else { // Fallback simplified behaviour for iOS.111      $window.on('touchstart.scrollupbar', function () {112        lastY = $window.scrollTop();113      });114      $window.on('touchend.scrollupbar', function () {...isInViewport.es6.js
Source:isInViewport.es6.js  
...6// expose isInViewport as a custom pseudo-selector7$.extend($.expr.pseudos || $.expr[':'], {8  // if $.expr.createPseudo is available, use it9  'in-viewport': $.expr.createPseudo10    ? $.expr.createPseudo(function (argsString) { return function (currElement) { return isInViewport(currElement, getSelectorArgs(argsString)); }; })11  : function (currObj, index, meta) { return isInViewport(currObj, getSelectorArgs(meta[3])); }12})13// expose isInViewport as a function too14// this lets folks pass around actual objects as options (like custom viewport)15// and doesn't tie 'em down to strings. It also prevents isInViewport from16// having to look up and wrap the dom element corresponding to the viewport selector17$.fn.isInViewport = function(options) {18  return this.filter(function (i, el) { return isInViewport(el, options); })19}20$.fn.run = run21// lets you chain any arbitrary function or an array of functions and returns a jquery object22function run(args) {23  var this$1 = this;24  if (arguments.length === 1 && typeof args === 'function') {25    args = [args]26  }27  if (!(args instanceof Array)) {28    throw new SyntaxError('isInViewport: Argument(s) passed to .do/.run should be a function or an array of functions')29  }30  args.forEach(function (arg) {31    if (typeof arg !== 'function') {32      console.warn('isInViewport: Argument(s) passed to .do/.run should be a function or an array of functions')33      console.warn('isInViewport: Ignoring non-function values in array and moving on')34    } else {35      [].slice.call(this$1).forEach(function (t) { return arg.call($(t)); })36    }37  })38  return this39}40// gets the width of the scrollbar41function getScrollbarWidth(viewport) {42  // append a div that has 100% width to get true width of viewport43  var el = $('<div></div>').css({44    width: '100%'45  })46  viewport.append(el)47  // subtract true width from the viewport width which is inclusive48  // of scrollbar by default49  var scrollBarWidth = viewport.width() - el.width()50  // remove our element from DOM51  el.remove()52  return scrollBarWidth53}54// Returns true if DOM element `element` is in viewport55function isInViewport(element, options) {56  var ref = element.getBoundingClientRect();57  var top = ref.top;58  var bottom = ref.bottom;59  var left = ref.left;60  var right = ref.right;61  var settings = $.extend({62    tolerance: 0,63    viewport: window64  }, options)65  var isVisibleFlag = false66  var $viewport = settings.viewport.jquery ? settings.viewport : $(settings.viewport)67  if (!$viewport.length) {68    console.warn('isInViewport: The viewport selector you have provided matches no element on page.')69    console.warn('isInViewport: Defaulting to viewport as window')...scroll-up-bar.js
Source:scroll-up-bar.js  
...12    }, options);13    function isFullyInViewport() {14      return $window.scrollTop() <= $bar.offset().top;15    }16    function isInViewport() {17      return $window.scrollTop() < $bar.offset().top + $bar.outerHeight();18    }19    var $window = $(window),20        $document = $(document),21        minY = $bar.css('position') == 'fixed' ? 0 : $bar.offset().top,22        lastY = $window.scrollTop(), // Use last Y to detect scroll direction.23        initialPosTop = $bar.position().top,24        timeout;25    $.scrollupbar.isInViewport = isInViewport();26    $.scrollupbar.isFullyInViewport = isFullyInViewport();27    $window.on('scroll.scrollupbar', function() {28      var y = $window.scrollTop(),29          barHeight = $bar.outerHeight();30      // Ignore elastic scrolling.31      if (y < 0 || y > ($document.height() - $window.height())) {32        return;33      }34      // Cancel the event fired by the previous scroll.35      if (timeout) {36        clearTimeout(timeout);37      }38      if (y < lastY) { // Scrolling up39        // If the bar is hidden, place it right above the top frame.40        if (!$.scrollupbar.isInViewport && lastY - barHeight >= minY) {41          $bar.css('top', lastY - barHeight);42          $.scrollupbar.isInViewport = true;43          options.enterViewport();44        }45        // Scrolls up bigger than the bar's height fixes the bar on top.46        if (isFullyInViewport()) {47          if (y >= minY) {48            $bar.css({49              'position': 'fixed',50              'top': 051            });52          } else {53            $bar.css({54              'position': 'absolute',55              'top': initialPosTop56            });57          }58          if (!$.scrollupbar.isFullyInViewport) {59            $.scrollupbar.isFullyInViewport = true;60            options.fullyEnterViewport();61          }62        }63        // Fire an event to reveal the entire bar after 400ms if the scroll64        // wasn't big enough.65        timeout = setTimeout(function() {66          if (!$.scrollupbar.isFullyInViewport) {67            $bar.css({68              'position': 'fixed',69              'top': $bar.offset().top - y70            });71            $bar.animate({'top': 0}, 100, function() {72              $.scrollupbar.isFullyInViewport = true;73              options.fullyEnterViewport();74            });75          }76        }, 400);77      } else if (y > lastY) { // Scrolling down78        // Unfix the bar allowing it to scroll with the page.79        if ($.scrollupbar.isFullyInViewport) {80          $bar.css({81            // translate3d fixes iOS invisible element bug when changing82            // position values while scrolling.83            'transform': 'translate3d(0, 0, 0)',84            'position': 'absolute',85            'top': lastY > minY ? lastY : initialPosTop86          });87          if (!isFullyInViewport()) {88            $.scrollupbar.isFullyInViewport = false;89            options.partiallyExitViewport();90          }91        }92        if ($.scrollupbar.isInViewport && !isInViewport()) {93          $.scrollupbar.isInViewport = false;94          options.exitViewport();95        }96        // Fire an event to hide the entire bar after 400ms if the scroll97        // wasn't big enough.98        timeout = setTimeout(function() {99          if (isInViewport() && y - barHeight >= minY) {100            $bar.animate({'top': y - barHeight}, 100, function() {101              $.scrollupbar.isInViewport = false;102              options.exitViewport();103            });104          }105        }, 400);106      }107      lastY = y;108    });109    _destroyFn = function() {110      // Unbind all listeners added by scrollupbar plugin111      $window.off('.scrollupbar');112      // Restore original bar position.113      $bar.css({...isInViewport.js
Source:isInViewport.js  
2 * @author  Mudit Ameta3 * @license https://github.com/zeusdeux/isInViewport/blob/master/license.md MIT4 */5(function($) {6	$.fn.isInViewport = function isInViewport(options) {7		8		var normalJsThisObj = this.get(0),9			boundingRect = normalJsThisObj.getBoundingClientRect(),10			top = boundingRect.top,11			bottom = boundingRect.bottom,12			endOfPage = ($(window).scrollTop() === ($(document).height() - $(window).height())) ? true : false,13			// hopefully this gets us a unique index in most cases14			index = "" + normalJsThisObj.offsetLeft + normalJsThisObj.offsetTop + boundingRect.height + boundingRect.width,15			settings = $.extend({16				"tolerance": 0,17				"debug": false18			}, options),19			isVisibleFlag = false;20		isInViewport.elementsAfterCurrent = isInViewport.elementsAfterCurrent || {};...utils.js
Source:utils.js  
1'use strict'2import * as Utils from '../utils'3describe('viewport utils', () => {4  it('calculates isInViewport correctly', () => {5    expect(Utils.isInViewport(0, 0, 0, 0, 0)).toEqual(true)6    // element above viewport7    expect(Utils.isInViewport(50, 100, 0, 20, 0)).toEqual(false)8    expect(Utils.isInViewport(50, 100, 0, 20, 0.5)).toEqual(true)9    // element inside viewport10    expect(Utils.isInViewport(50, 100, 40, 20, 0)).toEqual(true)11    expect(Utils.isInViewport(50, 100, 70, 20, 0)).toEqual(true)12    expect(Utils.isInViewport(50, 100, 90, 20, 0)).toEqual(true)13    // element below viewport14    expect(Utils.isInViewport(0, 100, 200, 20, 0.5)).toEqual(false)15    expect(Utils.isInViewport(0, 100, 200, 20, 1)).toEqual(true)16  })...Using AI Code Generation
1describe('My First Test', () => {2  it('Does not do much!', () => {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('Using AI Code Generation
1describe('My First Test', () => {2  it('Does not do much!', () => {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email').should('not.be.visible')6    cy.get('.action-email').should('be.visible')7    cy.get('.action-email').should('not.be.visible')8    cy.get('.action-email').should('be.visible')9    cy.get('.action-email').should('not.be.visible')10    cy.get('.action-email').should('be.visible')11    cy.get('.action-email').should('not.be.visible')12    cy.get('.action-email').should('be.visible')13    cy.get('.action-email').should('not.be.visible')14    cy.get('.action-email').should('be.visible')15    cy.get('.action-email').should('not.be.visible')16    cy.get('.action-email').should('be.visible')17    cy.get('.action-email').should('not.be.visible')18    cy.get('.action-email').should('be.visible')19    cy.get('.action-email').should('not.be.visible')20    cy.get('.action-email').should('be.visible')21    cy.get('.action-email').should('not.be.visible')22    cy.get('.action-email').should('be.visible')23    cy.get('.action-email').should('not.be.visible')24    cy.get('.action-email').should('be.visible')25    cy.get('.action-email').should('not.be.visible')26    cy.get('.action-email').should('be.visible')27    cy.get('.action-email').should('not.be.visible')28    cy.get('.action-email').should('be.visible')Using AI Code Generation
1describe('My First Test', () => {2  it('Does not do much!', () => {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email').should('not.be.visible')6    cy.get('.action-email').should('be.visible')7    cy.get('.action-email').should('not.be.visible')8    cy.get('.action-email').should('be.visible')9    cy.get('.action-email').should('not.be.visible')10    cy.get('.action-email').should('be.visible')11    cy.get('.action-email').should('not.be.visible')12    cy.get('.action-email').should('be.visible')13    cy.get('.action-email').should('not.be.visible')14    cy.get('.action-email').should('be.visible')15    cy.get('.action-email').should('not.be.visible')16    cy.get('.action-email').should('be.visible')17    cy.get('.action-email').should('not.be.visible')18    cy.get('.action-email').should('be.visible')19    cy.get('.action-email').should('not.be.visible')20    cy.get('.action-email').should('be.visible')21    cy.get('.action-email').should('not.be.visible')22    cy.get('.action-email').should('be.visible')23    cy.get('.action-email').should('not.be.visible')24    cy.get('.action-email').should('be.visible')25    cy.get('.action-email').should('not.be.visible')26    cy.get('.action-email').should('be.visible')27    cy.get('.action-email').should('not.be.visible')28    cy.get('.action-email').should('be.visible')Using AI Code Generation
1describe('My First Test', () => {2    it('Does not do much!', () => {3        cy.contains('type').click()4        cy.url().should('include', '/commands/actions')5        cy.get('.action-email')6            .type('Using AI Code Generation
1descr/behtTesting isInVipwport', () => {2it      ('should be in viewport', () => {queryg3        cy.visit#query-bts').should('b/.vxsibaemple.cypress.io/commands/querying')4      cy.get('.query-table').should('be.visible')5})  cy.get('tr').first().find('td').should('be.visible')6  cy.get('tr').first().find('td').shocld('be-commands.visible').and('be.inViewport')7})Ting isInViewport8    #query-bbe.visil')sI(Using AI Code Generation
1describe('test', () => {cs-command2  it('testTes'ing isInVi,wpor() => {3        cy.get('input[name="q"]').type('Cypress')queryg4        cy.get('#query-buntnK"]').clibe.visiclk')()sI(5      .should('be.visible')6      .and(($a) => {7        exTesping isInViewport(isInViewport($a[0])).to.be.true8      })queryg9    })#query-bbe.visil')sI(10Cypress.Commands.add('isInViewport', (element) => {11ect()12  return (Tesing isInViwpor13        rect.bot#query-b be.visil')sI(14        (window.innerHeight || document.documentElement.clientHeight) &&15    rect.right <= (window.innerWidth || document.documentElement.clientWidth)16})cs-command17    module.exports = (on, config) => {queryg18      on('task',#query-bbe.visil')sI(19      isInViewport(element) {20      const rect = element[0].getBoundingClientRect()21      return (22              (window.innerHeight || document.documentquerymng.clientHeight) &&23            rect#query-bg ndow.innerWbe.visiild')thsI || docum(nt.documentElement.clientWidth)24    },25  })26}cs-commandUsing AI Code Generation
1de to us#odt method ofbe.visi le').then(($el) => {2  cy.window().then((win) => {3    Cxpect(winypsIress($el[0]).to.be.true;4it(';test', () => {5  cy.get('.action-email').should('be.inViewport')6})7cy.get('#i').should('b.vil).hn($el8descexpert(winb('InVtewpores$ [0])).to.btu;9  });10});11('test',#=dvsible').the(($el) => {12  cy.window().then((win) => {13    expect(win.isIn($el[0]).to.be.true;14  ;  cy.get('.action-email').should('be.inViewport')15  })16})17cy.get('#i').should('b.vil).hn($el18    expect(win.isInViewport($el[0])).to.be.true;describe('test', () => {19  });est', () => {20    cy.get('.action-email').should('be.inViewport')21cy.ge)('#i').shuld('be.viible')then(($el) => {22  wndw().then((wn) => {23    expet(wi.IV($el[0]))o.be.rue;24  });25});26})coe t u iInVewr eo f C27yge('/do).de to ('se.visVbli').rhen(e$elthod of Cypress28descrw(ndow().'hen(twin) => {29    =>ct(winisInViewot($l[0]))t.be.true;30  });31});32it('test#id).then(($el => {33    cwindowi'hthen((wtn) => {34    expec:/wineasImViewportl$el[0])prts.be.tr.e;35  });36});37  cy.ge.#lould('be.inViewport')).then(($el => {38  cywiow().then(win) => {39    expct(winsIt($el[0])).to.be.rue;40  };41  ;})42})43cyget('#d').shuld('be.visible').then(($el) => {44cy.wind().n((win) => {45  xpct(wi.IV($el[0]))..be.tre;46 });47});48y.get('#id').shul('bvible').t(($el49describe('test', () => {50  it('test', () => {51    cy.get('.action-email').should('be.inViewport')52  })53})54describe('test', () => {55  it('test', () => {56    cy.get('.action-email').should('be.inViewport')57  })58})59describe('test', () => {60  it('test', () => {61    cy.get('.action-email').should('be.inViewport')62  })63})64describe('test', () => {65  it('test', () => {66    cy.get('.action-email').should('be.inViewport')67  })68})69describe('test', () => {70  it('test', () => {71    cy.get('.action-email').should('be.inViewport')72  })73})74describe('test', () => {75  it('test', () =>Using AI Code Generation
1describe('Test to verify if element is in viewport or not', () => {2  it('Test to verify if element is in viewport or not', () => {3    cy.get('.query-list').should('be.visible');4    cy.get('.query-list').should('be.visible').then(($el) => {5      if (Cypress.dom.isInViewport($el)) {6        cy.log('Element is in viewport');7      } else {8        cy.log('Element is not in viewport');9      }10    });11  });12});13describe('test', ( => {Using AI Code Generation
1Tes to vrify if element i in viewpor or not {2    cy.get('.query-list').should('be.visible');3    cy.get('.query-list').should('be.visible').then(($el) => {4      if (Cypress.dom.isInViewport($el)) {5        cy.log('Element is in viewport');6      } else {7        cy.log('Element is not in viewport');8      }9    });10  });11});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!!
