I decided to enhance the identification and interaction process in Protractor by adding a custom data attribute called data-test-id
to specific elements. To achieve this, I created a custom locator within the onPrepare
callback function in my conf.js
file. Here's the custom locator implementation:
onPrepare: function () {
by.addLocator('testId', function(value, parentElement) {
parentElement = parentElement || document;
var nodes = parentElement.querySelectorAll('[data-test-id]');
return Array.prototype.filter.call(nodes, function(node) {
return (node.getAttribute('[data-test-id]') === value);
});
});
}
One of the elements in my Angular app is an h1
tag containing the text 'Home'. I assigned the data-test-id
attribute to it as shown below:
<h1 data-test-id="test-element">Home</h1>
Furthermore, here is the test script written in Protractor:
test.js:
describe('Navigate to the website.', function() {
it('Should have the Heading as Home', function() {
browser.get('http://localhost:8888/#/');
browser.waitForAngular();
var textValue = 'Home';
var heading = element(by.testId('test-element'));
expect(heading.getText()).toEqual(textValue);
});
});
conf.js:
exports.config = {
//directConnect: true,
seleniumAddress: 'http://localhost:4444/wd/hub',
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['test.js'],
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
},
onPrepare: function () {
by.addLocator('testId', function(value, parentElement) {
parentElement = parentElement || document;
var nodes = parentElement.querySelectorAll('[data-test-id]');
return Array.prototype.filter.call(nodes, function(node) {
return (node.getAttribute('[data-test-id]') === value);
});
});
}
};
However, upon running the test, I encountered the following error message:
1) Navigate to the website. Should have the Heading as Home
Message: NoSuchElementError: No element found using locator: by.testId("test-element")
I need assistance in resolving this issue and making the test function correctly. Any insights would be greatly appreciated.