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

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: by link text, by button text, by field names, etc.
- Locator Builder
- ID locators: by CSS id or by accessibility id
- Custom Locator Strategies: by data attributes or whatever you prefer
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 witharia-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