In a previous post, I explained how I use the text associated with UI objects in my cucumber tests. My steps look something like this:
Given I go to the login page And I enter "johndoe" in the field with id "username" And I enter "password1" in the field with id "password"
If the application under test is using the <label> tag to identify form elements (and it should! The <label> tag was designed specifically for this purpose), then your application under test has UI objects that look something like this:
<label for="username">Username</label> <input name="username" type="text"></input>
Writing a cucumber step to interact with the <input> field based on the text in the <label> tag consists of locating the label element and then using the value of its for= attribute to locate the input element. Using the webdriver.io Selenium bindings, my code looks like this:
this.Given(/^I enter "([^"]*)" in the "([^"]*)" field$/, function (textToEnter, labelText, callback) { xpath = '//label[contains(.,"' + labelText + '")]'; this.getAttribute(xpath, 'for').then( function (value) { // get the input tag with the name= {value} and enter the text xpath = '//input[@name="' + value + '"]'; that.setValue(xpath, textToEnter).then( function () { callback(); }, function (err) { callback(err); } ); }, function (err) { callback(err); } ); });
One thought on “Identifying form elements by the <label> tag contents”
Comments are closed.