How to test if an element has class using Protractor?
If you're using Protractor with Jasmine, you could use toMatch
to match as a regular expression...
expect(element(by.name('getoffer')).getAttribute('class')).toMatch('ngDirty');
Also, note that toContain
will match list items, if you need that.
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);