Responsiveness Testing with Selenium WebDriver
How to use automated tests to test responsive websites in Selenium WebDriver
Most modern websites are responsive, which essentially means that depending on the window size, the appearance of the page changes. The most common example of this is a nav bar shrinking for mobile view.
This presents a challenge for End-To-End UI tests, as you will need to test responsive views too. This article will walk through how to write a test for a responsive website.
Test Design
I’ll use WhenWise as the sample app in the tutorial and try to access the sidebar. In the responsive view, the sidebar is replaced by the hamburger icon on the top-left.
I’ll just do a simple test to navigate to one of the sidebar links, “Reviews”.
Set browser size to desktop
Click Reviews
Change browser size to mobile
Ensure Reviews cannot be clicked directly; instead open the Hamburger menu then click Reviews.
Clearly, the key is how to resize the browser window. Luckily, this is very easy in Selenium.
Resizing browser window
In Selenium, you can set the browser dimensions with driver.manage.window.resize_to
, example:
# set window to width of 1280px and height of 900px
driver.manage.window.resize_to(1280, 900)
I recommend setting this in the before(:all)
step of your test file.
Desktop Version
Before we start with the responsive size, let’s create a baseline test for the regular desktop view. A standard window size is 1280px x 960px
, so I set that first.
it "Desktop view - access sidebar directly" do
driver.manage.window.resize_to(1280, 960)
sign_in("driving@biz.com")
expect(page_text).to_not include("Rating")
driver.find_element(:id, "menu-reviews").click
expect(page_text).to include("Rating")
sign_out
end
The rest of the test is pretty standard, just click the “Reviews” nav icon and verify we are on the Reviews page.
Responsive Version
For this test, resize the window to custom values instead.
driver.manage.window.resize_to(375, 667) # iphone8
I set the height and width to an iPhone 8 (a pretty standard phone size). Of course, you can set it to match a different phone’s dimensions or tablet size if you prefer.
Note that the body of the responsive test is different from the desktop one, because the website is different. Now we need to open the Hamburger menu first.
# open hamburger menu
driver.find_element(:xpath, "//a[@class='sidenav-trigger']").click
driver.find_element(:id, "menu-reviews").click
expect(page_text).to include("Rating")
And that’s it! It’s quite simple to resize the browser window in Selenium to simulate responsive devices.
Complete Test Script
Keep reading with a 7-day free trial
Subscribe to AgileWay’s Test Automation & Continuous Testing Blog to keep reading this post and get 7 days of free access to the full post archives.