How to test if an element has class using Protractor?

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'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.


Simplest is:

expect(element.getAttribute('class')).toContain("active");

Based on the answer from Sergey K, you could also add a custom matcher to do this:

(coffeescript)

  beforeEach(()->
    this.addMatchers({
      toHaveClass: (expected)->
        @message = ()->
          "Expected #{@actual.locator_.value} to have class '#{expected}'"

        @actual.getAttribute('class').then((classes)->
          classes.split(' ').indexOf(expected) isnt -1
        )
    })
  )

Then you can use it in tests like this:

expect($('div#ugly')).toHaveClass('beautiful')

And you'll get the following error if it doesn't:

 Message:
   Expected div#ugly to have class beautiful
 Stacktrace:
   Error: Expected div#ugly to have class 'beautiful'