Verify website layout changes on different screen sizes using cy.viewport()
Preconditions (2)
✅ Expected Result: The website layout changes according to the viewport size, showing mobile menu on small screens and full navigation on larger screens.
describe('Responsive layout test with cy.viewport()', () => { beforeEach(() => { cy.visit('https://example.cypress.io') }) it('shows mobile menu button on small screen', () => { cy.viewport(320, 480) cy.get('.mobile-menu-button').should('be.visible') }) it('shows navigation bar on tablet screen', () => { cy.viewport(768, 1024) cy.get('.navigation-bar').should('be.visible') }) it('shows full navigation menu on desktop screen', () => { cy.viewport(1280, 800) cy.get('.full-navigation-menu').should('be.visible') }) })
This test suite uses cy.viewport() to simulate different screen sizes: mobile, tablet, and desktop.
Each test visits the website fresh to avoid state carryover.
Selectors like .mobile-menu-button, .navigation-bar, and .full-navigation-menu represent elements expected to appear at each screen size.
Assertions use .should('be.visible') to confirm the correct layout is shown.
Cypress automatically waits for elements, so no manual waits are needed.
Now add data-driven testing to check the layout on these three screen sizes in a single test using an array of viewport sizes.
cy.viewport() in Cypress tests?cy.viewport()cy.viewport() syntaxcy.viewport(width, height).cy.viewport('iphone-6');
cy.viewport(800, 600);cy.viewport() call sets the final size.cy.viewport(1024);
cy.viewport(1024, 768).cy.viewport() multiple times to change screen size during a test.Pass the test and this pattern moves unknown