Wednesday, May 31, 2017

How to find & test CSS Selector using Chrome DevTools


1) Introduction
2) Chrome Developer Tools
3) CSS selector
4) Demo in Java

1) Introduction

I was surprised after seeing a couple of questions regarding selector verification. This triggered me to create this basic tutorial which hopefully would be useful for test automation newcomers. 

As a prerequisite you need to download & install Google Chrome browser (if not done already).

2) Chrome Developer Tools

Throughout this tutorial we would be using Chrome DevTools. In order to access it you need to press the following keys in Chrome:
a) Ctrl + Shift + I on Windows
b) Cmd + Opt (Alt) + I on Mac

You should see something like this (DevTools may also open at the bottom of the page)

Assuming you are testing websites I strongly advise you to get familiar with every single option. We would be using only two tabs:
a) Elements - page source used to find proper selectors
b) Console - browser console in which we would test our selectors

3a) CSS selector example A

Let's start with CSS selectors as they're usually shorter and easier to understand than XPath. Here are the steps to get header CSS selector:

a) Rightclick on header (big A) and pick Inspect - this should highlight header element in Elements tab

b) Rightclick on highlighted code and pick Copy -> Copy selector

c) Open Console tab

d) Type $$("") and paste copied selector between quotation marks. You should get something like this.

Thanks to those nice Chrome DevTools features we were able to find selector and also test it. This is very helpful especially when we have to deal with something more complicated.

3b) CSS selector example B

That was easy. Now let's assume we want to make sure number of displayed posts equals 5 on homepage. In order to achieve that I need to find post title selector and make sure it occurs exactly 5 times. Here are steps:

a) Inspecting element in Chrome DevTools leads us here

b) I'm seeing that all titles are h1 and with class post-title. What's the selector then? It's

c) Verification in Console confirms that we have found proper selector.

3c) How can I learn how to build CSS Selectors?

There is good and free tutorial available on w3schools site. It's extremely important for every aspiring test engineer to get familiar with it. It's a must have... especially before job interview :)

4) Demo in Java

I have prepared working demo for my readers. You can find it on my GitHub Awesome Testing project. I'm using FluentLenium and Page Object Pattern framework. That's how the HomePage class would look like.

And two simple tests. You should understand them instantly (at least that was my aim).