How to Check if Element is in Viewport in Cypress

How to Check if Element is in Viewport in Cypress

Ferenc Almasi β€’ 2021 October 19 β€’ Read time 2 min read
  • twitter
  • facebook

To check if an element is in the viewport in Cypress, we can add a custom assertion to Chai using the support folder. Create a new file called inViewport.js and export the following function:

Copied to clipboard! Playground
export default _chai => {
    function assertIsInViewport() {
        const subject = this._obj;

        const bottom = Cypress.$(cy.state('window')).height();
        const width = Cypress.$(cy.state('window')).width();
        const rect = subject[0].getBoundingClientRect();

        this.assert(
            rect.top < bottom && rect.right <= width && rect.left >= 0,
            'expected #{this} to be in the viewport',
            'expected #{this} to not be in the viewport',
            this._obj
        );
    }

    _chai.Assertion.addMethod('inViewport', assertIsInViewport);
}
inViewport.js

This function will add a new assertion to Chai. Using this.assert, we can verify if the subject (the element that the assertion is chained from) is within the viewport or not. We can also define error messages as the second and third parameters of this function, and even pass the subject using #{this}.

In order to use this new assertion, inside the index.js file in your support folder, import it, and assign it to Chai:

Copied to clipboard! Playground
import inViewport from './inViewport'

before(() => {
    chai.use(inViewport);
});
index.js

This before hook will run once before all test files and adds the new assertion to Chai. Now you can call these assertions in the following way in your test cases:

Copied to clipboard!
cy.get('h1').should('be.inViewport');
cy.get('h1').should('not.be.inViewport');

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Check if Element is in Viewport in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.