Disable all horizontal scrollbars in Cypress

Viewed 529

Is there a way to apply a style to all elements in Cypress? Like one would do with the star selector:

* {
  overflow-x: hidden;
}

I need this for visual regression snapshots, because of scrollbars that appear, and haven't been able to find something simple and elegant in Cypress. Currently doing something like this:

cy.get('[data-cy="some-tag"]').invoke('css', 'overflow-x', 'hidden');

But of course this isn't great, because every element that has scrollbars has to be targetted and set.

1 Answers

You can change the DOM just before any screenshot is taken by using onBeforeScreenshot and onAfterScreenshot callbacks. This will hide the scrollbar on the element the screenshot command was called on, and restore it afterwards:

Cypress.Screenshot.defaults({
    onBeforeScreenshot($el) {
        $el.css('overflow', 'hidden');
    },

    onAfterScreenshot($el, props) {
        $el.css('overflow', 'auto');
    },
});

You can put this function in support/index.js file since it is loaded before any test files.

Note: if you just call cy.screenshot() then the $el will be the document and you can use .find(<selector>) command to get any child elements within the page.

Works great with cypress-visual-regression plugin.

Reference: https://docs.cypress.io/api/cypress-api/screenshot-api#Change-the-DOM-using-onBeforeScreenshot-and-onAfterScreenshot

Related