Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if an element has class using Protractor?

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     }); }); 
like image 758
Allan Tatter Avatar asked Nov 28 '13 14:11

Allan Tatter


People also ask

Can a element have class?

HTML elements can have an id and/or class attribute.

How do you find the ID of an element on a protractor?

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.


1 Answers

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); 
like image 142
Sergey K Avatar answered Sep 22 '22 23:09

Sergey K