Skip to content

Commit

Permalink
Add regex support for class assertion
Browse files Browse the repository at this point in the history
  • Loading branch information
SevenOutman committed Sep 18, 2021
1 parent 7a83d08 commit 0ad45ed
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions chai-dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@

chai.Assertion.addMethod('class', function(className) {
var el = flag(this, 'object')

if (className instanceof RegExp) {
return this.assert(
Array.from(el.classList).some(function(cls) { return className.test(cls) })
, 'expected ' + elToString(el) + ' to have class matching #{exp}'
, 'expected ' + elToString(el) + ' not to have class matching #{exp}'
, className
)
}

this.assert(
el.classList.contains(className)
, 'expected ' + elToString(el) + ' to have class #{exp}'
Expand Down
20 changes: 20 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,21 +132,41 @@ describe('DOM assertions', function() {
subject.should.have.class('baz');
})

it('passes when the element has the class matching given regex', function () {
subject.should.have.class(/foo/)
})

it('passes negated when the element does not have the class', function() {
subject.should.not.have.class('bar')
})

it('passes negated when the element does not have the class matching given regex', function () {
subject.should.not.have.class(/bar/)
})

it('fails when the element does not have the class', function() {
(function() {
subject.should.have.class('bar')
}).should.fail('expected div.foo.shazam.baz to have class \'bar\'')
})

it('fails when the element does not have the class matching given regex', function() {
(function() {
subject.should.have.class(/bar/)
}).should.fail('expected div.foo.shazam.baz to have class matching /bar/')
})

it('fails negated when the element has the class', function() {
(function() {
subject.should.not.have.class('foo')
}).should.fail('expected div.foo.shazam.baz not to have class \'foo\'')
})

it('fails negated when the element has the class matching given regex', function() {
(function() {
subject.should.not.have.class(/foo/)
}).should.fail('expected div.foo.shazam.baz not to have class matching /foo/')
})
})

describe('id', function() {
Expand Down

0 comments on commit 0ad45ed

Please sign in to comment.