Bird
Raised Fist0
Cypresstesting~15 mins

cy.viewport() for screen sizes in Cypress - Deep Dive

Choose your learning style10 modes available
Overview - cy.viewport() for screen sizes
What is it?
cy.viewport() is a command in Cypress that lets you change the size of the browser window during tests. It helps simulate how a website looks and behaves on different screen sizes like phones, tablets, or desktops. This way, you can check if your site works well on all devices without needing real hardware. It is simple to use and essential for responsive design testing.
Why it matters
Without cy.viewport(), testers would struggle to verify if a website adapts correctly to various screen sizes. This could lead to poor user experiences on mobile or tablet devices, causing frustration and lost customers. By using cy.viewport(), you catch layout or functionality issues early, saving time and money. It ensures your website is accessible and user-friendly everywhere.
Where it fits
Before learning cy.viewport(), you should understand basic Cypress commands and how to write simple tests. After mastering it, you can explore advanced responsive testing techniques, like testing different device orientations or combining viewport changes with network conditions. It fits into the broader journey of end-to-end testing and cross-device compatibility.
Mental Model
Core Idea
cy.viewport() changes the browser window size during tests to mimic different device screens and check responsive behavior.
Think of it like...
It's like adjusting the size of a picture frame to see how a photo looks when cropped differently, ensuring the important parts are always visible.
┌───────────────────────────────┐
│          cy.viewport()         │
├───────────────┬───────────────┤
│ Input: width  │ Input: height │
├───────────────┼───────────────┤
│ Changes browser window size   │
│ to simulate device screens    │
├───────────────┴───────────────┤
│ Result: Website layout adapts │
│ and functionality tested      │
└───────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding viewport basics
🤔
Concept: Learn what a viewport is and why its size matters in web testing.
The viewport is the visible area of a web page in a browser window. Different devices have different viewport sizes, like a phone screen is smaller than a desktop monitor. Websites often change their layout based on viewport size to look good everywhere. Testing with different viewport sizes helps ensure the site works well on all devices.
Result
You understand that viewport size controls how a website appears and behaves on different devices.
Knowing the viewport is the window through which users see your site helps you realize why testing different sizes is crucial for user experience.
2
FoundationBasic usage of cy.viewport()
🤔
Concept: Learn how to use cy.viewport() to set browser size in Cypress tests.
In Cypress, you use cy.viewport(width, height) to set the browser window size. For example, cy.viewport(375, 667) simulates an iPhone 6 screen. You place this command in your test before visiting a page or interacting with elements. This changes the test browser size so you can check how the page looks and behaves.
Result
You can run tests that simulate different screen sizes by changing the viewport.
Understanding how to set viewport size manually lets you test specific device dimensions easily.
3
IntermediateUsing predefined device presets
🤔Before reading on: do you think cy.viewport() requires exact pixel sizes only, or can it use device names? Commit to your answer.
Concept: Cypress offers named presets for common devices to simplify viewport setting.
Instead of typing width and height, you can use cy.viewport('iphone-6') or cy.viewport('ipad-2'). These presets automatically set the viewport to the device's screen size and pixel ratio. This saves time and reduces errors. You can find a list of supported devices in Cypress documentation.
Result
Tests become easier to write and read by using device names instead of numbers.
Knowing device presets speeds up testing and improves clarity, making tests more maintainable.
4
IntermediateTesting orientation changes
🤔Before reading on: do you think cy.viewport() can simulate device rotation (portrait vs landscape)? Commit to your answer.
Concept: cy.viewport() can change orientation to test how layouts adapt when devices rotate.
You can add a second argument to cy.viewport() to set orientation: 'portrait' or 'landscape'. For example, cy.viewport('ipad-2', 'landscape') switches the viewport to landscape mode. This helps test responsive designs that change layout or behavior when the device rotates.
Result
You can verify that your site works well in both portrait and landscape modes.
Testing orientation ensures your site adapts to real user behavior, improving usability.
5
AdvancedCombining viewport with responsive assertions
🤔Before reading on: do you think changing viewport alone guarantees responsive correctness? Commit to your answer.
Concept: Viewport changes must be paired with assertions that check layout or element visibility to confirm responsiveness.
After setting viewport, write assertions to check if elements appear, hide, or reposition correctly. For example, check if a mobile menu button is visible on small screens but hidden on large screens. This confirms your responsive design works as intended, not just that the window size changed.
Result
Tests verify actual responsive behavior, not just viewport size changes.
Understanding that viewport is a tool, but assertions confirm correctness, leads to meaningful tests.
6
ExpertHandling viewport limitations and edge cases
🤔Before reading on: do you think cy.viewport() perfectly mimics all device behaviors? Commit to your answer.
Concept: cy.viewport() changes window size but cannot simulate all device features like touch events or pixel density perfectly.
While cy.viewport() adjusts size and orientation, it does not emulate device hardware like touchscreens or exact pixel ratios. Some CSS media queries based on device features may not trigger exactly. For full device testing, use real devices or device emulators alongside Cypress. Also, some browsers may have minimum window sizes that limit viewport changes.
Result
You know when cy.viewport() is enough and when to use additional testing tools.
Recognizing cy.viewport() limits prevents false confidence and encourages comprehensive testing strategies.
Under the Hood
cy.viewport() works by instructing the browser controlled by Cypress to resize its window or viewport area to specified dimensions. Internally, Cypress sends commands to the browser's automation protocol to adjust the viewport size before running test commands. This resizing triggers the browser's layout engine to reflow and repaint the page as if viewed on a device with that screen size.
Why designed this way?
Cypress was designed to provide fast, reliable end-to-end tests without needing real devices. Changing viewport size programmatically allows simulating many devices quickly. Alternatives like using real devices or emulators are slower and harder to automate. This approach balances speed, simplicity, and coverage for responsive testing.
┌───────────────┐       ┌─────────────────────┐
│ Cypress Test  │──────▶│ Browser Automation  │
│  Script       │       │ Protocol (resize)   │
└───────────────┘       └─────────┬───────────┘
                                    │
                                    ▼
                         ┌─────────────────────┐
                         │ Browser Viewport    │
                         │ Resized to new size │
                         └─────────┬───────────┘
                                   │
                                   ▼
                         ┌─────────────────────┐
                         │ Page Layout Engine  │
                         │ Reflows & repaints  │
                         └─────────────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Does cy.viewport() simulate all device features like touch and pixel density? Commit to yes or no.
Common Belief:cy.viewport() fully simulates the device, including touch events and pixel density.
Tap to reveal reality
Reality:cy.viewport() only changes the browser window size and orientation; it does not simulate hardware features like touch or exact pixel density.
Why it matters:Relying solely on cy.viewport() can miss bugs related to touch interactions or high-resolution displays, leading to incomplete testing.
Quick: If you set cy.viewport() once, does it apply to all tests automatically? Commit to yes or no.
Common Belief:Setting cy.viewport() once applies the size to all tests in the suite.
Tap to reveal reality
Reality:cy.viewport() affects only the current test or command chain; each test should set viewport explicitly if needed.
Why it matters:Tests may behave inconsistently if viewport is not set per test, causing flaky or misleading results.
Quick: Does cy.viewport() accept any arbitrary device name? Commit to yes or no.
Common Belief:You can use any device name string with cy.viewport() and it will work.
Tap to reveal reality
Reality:cy.viewport() supports only predefined device names listed in Cypress documentation; unknown names cause errors.
Why it matters:Using unsupported device names leads to test failures and confusion.
Expert Zone
1
Some CSS media queries rely on device pixel ratio or features not affected by cy.viewport(), so tests may need additional setup or real devices.
2
Changing viewport size mid-test can cause layout thrashing; it's best to set viewport once per test to avoid flaky behavior.
3
Combining cy.viewport() with network throttling or user agent changes can simulate more realistic device conditions for advanced testing.
When NOT to use
Do not rely on cy.viewport() alone for testing device-specific hardware features like touch gestures or camera access. Use real device testing or specialized emulators for those cases. Also, for visual regression testing, consider dedicated tools that capture screenshots across devices.
Production Patterns
In real projects, cy.viewport() is used in test suites to run the same test scenarios across multiple screen sizes automatically. Teams often create helper functions to loop through device presets and orientations. It is combined with assertions checking element visibility, layout changes, and interactive behavior to ensure responsive design quality.
Connections
Responsive Web Design
cy.viewport() tests how responsive design adapts to different screen sizes.
Understanding cy.viewport() deepens your grasp of responsive design by showing how layout changes under different viewport conditions.
Cross-Browser Testing
Both cy.viewport() and cross-browser testing ensure consistent user experience across environments.
Knowing viewport testing complements cross-browser testing helps build comprehensive UI test strategies.
Photography Framing
Changing viewport size is like cropping a photo to focus on different parts.
This connection shows how adjusting visible area affects perception, similar to how viewport size affects website layout.
Common Pitfalls
#1Not setting viewport size in each test causes inconsistent test results.
Wrong approach:describe('Test suite', () => { before(() => { cy.viewport('iphone-6') }) it('Test 1', () => { cy.visit('/') // test code }) it('Test 2', () => { cy.visit('/') // test code }) })
Correct approach:describe('Test suite', () => { beforeEach(() => { cy.viewport('iphone-6') }) it('Test 1', () => { cy.visit('/') // test code }) it('Test 2', () => { cy.visit('/') // test code }) })
Root cause:Misunderstanding that viewport setting persists across tests, when it actually resets.
#2Using unsupported device names causes test failures.
Wrong approach:cy.viewport('unknown-device')
Correct approach:cy.viewport('iphone-6')
Root cause:Assuming any string works as a device preset without checking Cypress documentation.
#3Expecting cy.viewport() to simulate touch events leads to missed bugs.
Wrong approach:cy.viewport('iphone-6') // test touch gestures without additional setup
Correct approach:// Use real device or emulator for touch tests // cy.viewport() only changes size, not touch support
Root cause:Confusing viewport size simulation with full device feature emulation.
Key Takeaways
cy.viewport() is a Cypress command that changes the browser window size to simulate different device screens during tests.
Using viewport presets like 'iphone-6' simplifies testing common devices without remembering exact dimensions.
Testing both portrait and landscape orientations helps ensure responsive designs adapt correctly to device rotation.
Viewport changes must be combined with assertions to verify actual responsive behavior, not just window size.
cy.viewport() does not simulate all device features; for full device testing, use real devices or emulators alongside Cypress.

Practice

(1/5)
1. What is the main purpose of using cy.viewport() in Cypress tests?
easy
A. To change the screen size and test responsive layouts
B. To select elements on the page
C. To wait for an element to appear
D. To take screenshots of the page

Solution

  1. Step 1: Understand the function of cy.viewport()

    This command sets the browser's screen size to simulate different devices or resolutions.
  2. Step 2: Identify the purpose in testing

    Changing screen size helps test how the website looks and behaves on various devices, ensuring responsive design works.
  3. Final Answer:

    To change the screen size and test responsive layouts -> Option A
  4. Quick Check:

    cy.viewport() changes screen size = D [OK]
Hint: Remember: viewport changes screen size for responsive tests [OK]
Common Mistakes:
  • Confusing viewport with element selectors
  • Thinking viewport waits for elements
  • Assuming viewport takes screenshots
2. Which of the following is the correct syntax to set the viewport size to 1024 pixels wide and 768 pixels tall in Cypress?
easy
A. cy.viewport({width: 1024, height: 768});
B. cy.viewport(1024, 768);
C. cy.viewport('1024x768');
D. cy.setViewport(1024, 768);

Solution

  1. Step 1: Recall the correct cy.viewport() syntax

    The command accepts width and height as two separate number arguments: cy.viewport(width, height).
  2. Step 2: Check each option

    cy.viewport(1024, 768); uses two numbers correctly. cy.viewport('1024x768'); uses a string which is invalid. cy.viewport({width: 1024, height: 768}); uses an object which is not supported. cy.setViewport(1024, 768); uses a wrong command name.
  3. Final Answer:

    cy.viewport(1024, 768); -> Option B
  4. Quick Check:

    cy.viewport(width, height) = C [OK]
Hint: Use two numbers, not strings or objects, in cy.viewport() [OK]
Common Mistakes:
  • Passing size as a string like '1024x768'
  • Using an object instead of two numbers
  • Typing wrong command name like cy.setViewport
3. What will be the viewport size after running this Cypress code?
cy.viewport('iphone-6');
cy.viewport(800, 600);
medium
A. 800 pixels wide and 600 pixels tall
B. iPhone 6 preset size
C. Default viewport size
D. Test will fail due to conflicting viewport commands

Solution

  1. Step 1: Understand command order in Cypress

    Commands run in order. The last cy.viewport() call sets the final size.
  2. Step 2: Analyze the code

    First sets viewport to iPhone 6 size, then immediately changes it to 800x600 pixels.
  3. Final Answer:

    800 pixels wide and 600 pixels tall -> Option A
  4. Quick Check:

    Last cy.viewport() sets size = B [OK]
Hint: Last cy.viewport() call overrides previous sizes [OK]
Common Mistakes:
  • Thinking first viewport call persists
  • Assuming test fails on multiple viewport calls
  • Confusing preset names with pixel sizes
4. You wrote this code but the viewport size does not change as expected:
cy.viewport(1024);

What is the problem?
medium
A. Viewport size must be set before visiting the page
B. cy.viewport() does not accept numbers
C. Missing height argument in cy.viewport()
D. cy.viewport() only accepts device names

Solution

  1. Step 1: Check the cy.viewport() parameters

    The command requires both width and height as numbers, e.g., cy.viewport(1024, 768).
  2. Step 2: Identify the error

    Only width (1024) is provided, height is missing, so viewport size won't change correctly.
  3. Final Answer:

    Missing height argument in cy.viewport() -> Option C
  4. Quick Check:

    Both width and height needed = A [OK]
Hint: Always provide width and height numbers in cy.viewport() [OK]
Common Mistakes:
  • Passing only one number instead of two
  • Thinking cy.viewport accepts only device names
  • Believing viewport must be set before visiting page
5. You want to test your website's mobile and desktop views in one test. Which code snippet correctly sets the viewport to iPhone X size, runs a test, then changes to desktop size 1280x720 and runs another test?
hard
A. cy.viewport('iphone-x');\ncy.viewport(1280, 720);\ncy.get('#menu').should('be.visible');
B. cy.viewport('iphone-x', 1280, 720);\ncy.get('#menu').should('be.visible');
C. cy.viewport(1280, 720);\ncy.viewport('iphone-x');\ncy.get('#menu').should('be.visible');
D. cy.viewport('iphone-x');\ncy.get('#menu').should('be.visible');\ncy.viewport(1280, 720);\ncy.get('#menu').should('be.visible');

Solution

  1. Step 1: Understand sequential viewport changes

    You can call cy.viewport() multiple times to change screen size during a test.
  2. Step 2: Check the code snippets

    cy.viewport('iphone-x');\ncy.get('#menu').should('be.visible');\ncy.viewport(1280, 720);\ncy.get('#menu').should('be.visible'); sets iPhone X viewport, runs a check, then sets desktop viewport and runs the check again. This tests both views properly. cy.viewport('iphone-x', 1280, 720);\ncy.get('#menu').should('be.visible'); uses invalid syntax with multiple arguments. cy.viewport(1280, 720);\ncy.viewport('iphone-x');\ncy.get('#menu').should('be.visible'); changes viewport twice before any check. cy.viewport('iphone-x');\ncy.viewport(1280, 720);\ncy.get('#menu').should('be.visible'); runs only one check after both viewport changes, missing the first test.
  3. Final Answer:

    Set viewport, test, change viewport, test again -> Option D
  4. Quick Check:

    Change viewport before each test step = A [OK]
Hint: Call cy.viewport() before each test step to change screen size [OK]
Common Mistakes:
  • Passing multiple sizes in one cy.viewport() call
  • Changing viewport without running tests between
  • Running tests only after last viewport change
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard