Overview

The variety of devices users access the internet with are increasing rapidly and it becomes more important to ensure that your website or web application works as expected across all devices with varying screen sizes.

With Chrome DevTools Protocol support now available in Selenium 4, Nightwatch supports testing on varying screen dimensions. You can override the values of the screen dimensions in a test with just a single command. Along with that, you can also emulate a mobile device for loading your website, and change the device-scale-factor/device-pixel-ratio of your website as well.

The `setDeviceDimensions()` command only works with Chromium based browsers such as Google Chrome and Microsoft Edge.

Override device dimensions

Overriding the device dimensions while running your tests allows you to test how your website loads on different screen dimensions, without actually testing them on devices with different screen sizes. This is especially useful while testing the responsiveness of your website.

All you need to do is call the browser.setDeviceDimensions() command with the required parameters before navigating to your website.

setDeviceDimensions() accepts an object as its first argument. The specifications of the object are as follows:

key type default description
width number 0 Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override.
height number 0 Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override.
deviceScaleFactor
optional
number 0 Overriding device scale factor value. 0 disables the override.
mobile
optional
boolean false Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more.

Example

tests/modify-device-dimensions.js
describe('modify device dimensions', function() {
  it('modifies the device dimensions', function() {
    browser
      .setDeviceDimensions({
        width: 400,
        height: 600,
        deviceScaleFactor: 50,
        mobile: true
      })
      .navigateTo('https://www.google.com')
      .pause(1000);
  });
});

Reset device dimensions

To reset the device dimensions back to original, you can again call the browser.setDeviceDimensions() command, but without any arguments this time.

Example:

tests/modify-and-reset-device-dimensions.js
describe('modify device dimensions', function() {
  it('modifies the device dimensions and then resets it', function() {
    browser
      .setDeviceDimensions({
        width: 400,
        height: 600,
        deviceScaleFactor: 50,
        mobile: true
      })
      .navigateTo('https://www.google.com')
      .pause(1000)
      .setDeviceDimensions()  // resets the device dimensions
      .navigateTo('https://www.google.com')
      .pause(1000);
  });
});