Cypress Viewport Not Resizing Fix
In this tutorial, you'll learn about Cypress Viewport Not Resizing Fix. We cover key concepts, practical examples, and best practices.
Your responsive test fails — elements visible on desktop are hidden on mobile, but the viewport change doesn't trigger the expected layout shift.
The Problem
// WRONG — viewport changed after assertions
cy.viewport('iphone-6');
cy.visit('/');
cy.viewport('macbook-15');
cy.get('.desktop-menu').should('be.visible'); // Passes — but viewport was just changed
The test changes viewport but doesn't wait for the responsive layout to re-render. CSS media queries need a moment to apply.
Step-by-Step Fix
1. Set viewport before page load
// RIGHT — viewport before visit
cy.viewport('iphone-6');
cy.visit('/');
// Page renders in mobile viewport
cy.get('.mobile-menu').should('be.visible');
cy.get('.desktop-menu').should('not.be.visible');
2. Test multiple viewports
// RIGHT — responsive testing
const viewports = ['iphone-6', 'ipad-2', 'macbook-15'];
viewports.forEach((viewport) => {
it(`displays correctly on ${viewport}`, () => {
cy.viewport(viewport);
cy.visit('/');
cy.screenshot(`homepage-${viewport}`);
});
});
3. Use custom dimensions
// RIGHT — custom viewport sizes
cy.viewport(375, 667); // iPhone SE
cy.viewport(390, 844); // iPhone 14
cy.viewport(1024, 768); // iPad
cy.viewport(1920, 1080); // Full HD
4. Configure default viewport
// RIGHT — cypress.config.js
module.exports = {
e2e: {
viewportWidth: 1280,
viewportHeight: 720,
viewportPreset: 'macbook-15',
},
};
Expected output:
✓ mobile viewport
✓ displays correctly on iphone-6
✓ displays correctly on macbook-15
Prevention Tips
- Set viewport before
cy.visit()for consistent rendering - Test critical viewports: mobile, tablet, desktop
- Use named presets (
iphone-6,macbook-15) or custom sizes - Take screenshots at each viewport for visual comparison
- Configure default viewport in Cypress config
Common Mistakes with viewport
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world CYPRESS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro