I'm trying out Protractor to e2e test Angular app and haven't figured out how to detect if an element has a specific class or not.
In my case, the test clicks on submit button and now I want to know if form[name="getoffer"] has class .ngDirty. What may be the solutions?
describe('Contact form', function() { beforeEach(function(){ browser.get('http://localhost:9000'); element(by.linkText('Contact me')).click(); }); it('should fail form validation, all fields pristine', function() { element(by.css('.form[name="getoffer"] input[type="submit"]')).click(); expect(element(by.name('getoffer'))).toHaveClass('ngDirty'); // <-- This line }); });
HTML elements can have an id and/or class attribute.
To find an element in another element we use chaining of locators. First we need to find the parent element then using the parent element we find the child element and perform operation on it. var parent = element(by.id('get-input')); var child = parent.
One gotcha you have to look out for with using toMatch()
, as in the accepted answer, is partial matches. For instance, let's say you have an element that might have the classes correct
and incorrect
, and you want to test that it has the class correct
. If you were to use expect(element.getAttribute('class')).toMatch('correct')
, that will return true even if the element has the incorrect
class.
My suggestion:
If you want to only accept exact matches, you can create a helper method for it:
var hasClass = function (element, cls) { return element.getAttribute('class').then(function (classes) { return classes.split(' ').indexOf(cls) !== -1; }); };
You can use it like this (taking advantage of the fact that expect
automatically resolves promises in Protractor):
expect(hasClass(element(by.name('getoffer')), 'ngDirty')).toBe(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With