End to end testing with NodeJS using CodeceptJS with real world example — Part 2(a): Locating Common Elements

Shivam Gohel
2 min readJan 12, 2022

If you haven’t looked at the previous article where we talk about the basics and the underlying architecture of CodeceptJS, please navigate here.

In the previous article, we executed our first test case using Puppeteer as our default helper. We will continue with the example, and explore different strategies for locating elements.

Locating Element

CodeceptJS provides flexible strategies for locating elements:

CSS and Xpath Locators

Semantic Locators

CodeceptJS can guess an element’s locator from context. For example, when clicking CodeceptJS will try to find a link or button by their text When typing into a field this field can be located by its name, placeholder.

I.click('Sign In');
I.fillField('Username', 'davert');

Various strategies are used to locate semantic elements. However, they may run slower than specifying locator by XPath or CSS.

Locator Builder

CodeceptJS provides a fluent builder to compose custom locators in JavaScript. Use locate function to start.

To locate a element inside label with text: 'Hello' use:

locate('a')
.withAttr({ href: '#' })
.inside(locate('label').withText('Hello'));

which will produce following XPath:

.//a[@href = '#'][ancestor::label[contains(., 'Hello')]]

locate has the following methods:

  • find — Finds an element inside a located.
  • withAttr — Find an element with provided attributes
  • withChild — Finds an element which contains a child element provided:
  • withDescendant — Finds an element which contains a descendant element provided
  • withText — Finds element containing a text

and many more. Refer this for more methods.

locate('table').find('td');
locate('input').withAttr({ placeholder: 'Type in name' });
locate('form').withChild('select');
locate('span').withText('Warning');

ID Locators

ID locators are best to select the exact semantic element in web and mobile testing:

  • #user or { id: 'user' } finds element with id="user"
  • ~user finds element with accessibility id "user" (in Mobile testing) or with aria-label=user

End Note 📝: We will use this strategies in the real world project that we are going to build in the upcoming articles.

In the next chapter, we will see how to locate react elements using codeceptJS

--

--

Shivam Gohel

I enable enterprises in launching high-quality products | M.S in Human Centered Design @ UMBC