12

How to check if an element has multiple classes? Couldn't find anything on the official docs, only:

cy.get('form').find('input').should('have.class', 'disabled')

or

expect($el).to.have.class('foo')

When inserting multiple class names, I get an error:

expect($el).to.have.class('foo bar baz')

Is there a solution?

Zach Bloomquist
  • 5,309
  • 29
  • 44
nikitahl
  • 406
  • 2
  • 7
  • 16

2 Answers2

20

One way is to chain multiple assertions together using cy.and():

cy.get('div')
.should('have.class', 'foo')
.and('have.class', 'bar')
.and('have.class', 'baz')
Zach Bloomquist
  • 5,309
  • 29
  • 44
  • Thanks. Although I expected something like passing multiple class strings in a sinle assertion, but I guess that's the way to go. – nikitahl May 17 '19 at 20:08
  • 4
    Well, if you have an element like `
    `, `cy.get('div').should('have.class', 'a b c')` will actually pass - but ONLY if the `class` attribute is exactly "a b c". So it's not a good idea to rely on this.
    – Zach Bloomquist May 17 '19 at 20:10
  • Oh, in my case it wasn't `a b c`, so that's why it failed! – nikitahl May 17 '19 at 20:13
0

One can certainly use a little helper function BUT it only makes sense with longer class lists as it adds two more lines to your test code.

Helper function:

function shouldHaveClasses(el, classList = []) {
  classList.forEach((c) => {
    expect(el).to.have.class(c)
  })
}

Your test:

describe('My Test', () => {
  cy.get('div')
    .then((el) => {
      shouldHaveClasses(el, ['foo', 'bar', 'baz'])
    })
})
Hexodus
  • 12,361
  • 6
  • 53
  • 72