Embrace the Power of CSS

When working with targets or methods such as *. assertNodeCount besides generic CSS selectors we can use Pseudo classes and Attribute selectors. Let’s take a look at some real-world example to discover what advantages it can bring us

Forms

Imagine we have a form

<form>
  <input
      type="email"
      required
      name="email"
      placeholder="Enter email" />
      
  <input
      type="text"
      required
      name="zip"
      pattern="^\d{5}$"
      placeholder="Enter ZIP code" />    
      
   <button type="submit">Submit</button>   
</form>

With the test case we seed the form with data and submit the form. Then we want to assert that there are no inputs in invalid state (see also HTML5 Constraint Validation API) So we use FORM.assertNodeCount method to look for input:invalid

If any of test values do not pass the validation (empty value, invalid email address, invalid ZIP) the assertion will fail.

What is more, we can assert that a checkbox control is checked with target.assertMatchesSelector method:

Lists

Imagine we have a blog app. We are testing article details page and want to ensure the social sharing links are not broken. Let’s say a simplified layout for the block is following:

<ul id="social">
  <li><a href="https://www.facebook.com/...">Share via Facebook</a></li>
  <li><a href="https://twitter.com/...">Share via Twitter</a></li>  
</ul>

So we create targets SHARE_FACEBOOK and SHARE_TWITTER

The trick here is that href attribute of share links in reality is a long string and also dynamic (depends on the page), but we go with attribute selector and target any links whose href contains a keyword (e.g. facebook.com). Thus we distinguish facebook and twitter links. Now we can assert availability and visibility:

We can assert that the links are provided with text description:

The selector :not(:empty) will be matched only if the link has text or child nodes.

In-page Navigation

Imagine we have a page with internal links. When user follows such a link the page changes its hash and scrolls to the anchored content or changes UI state. In our case we have a tabbed UI component, which opens the tab with desired content when page hash is #chapter1. If we want to assert the internal link is followed we use page.assertNodeCount

Last updated