Skip to content

Commit

Permalink
Merge pull request #54 from SevenOutman/feat/class-regex
Browse files Browse the repository at this point in the history
Add regex support for `.class` assertion
  • Loading branch information
nathanboktae committed Sep 21, 2021
2 parents 7a83d08 + d535fba commit 631d720
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Expand Up @@ -29,6 +29,13 @@ document.getElementsByName('bar').should.have.class('foo')
expect(document.querySelector('main article')).to.have.class('foo')
```

Also accepts regex as argument.

```js
document.getElementsByName('bar').should.have.class(/foo/)
expect(document.querySelector('main article')).to.have.class(/foo/)
```

### `id(id)`
Assert that the [HTMLElement][] has the given id.

Expand Down
10 changes: 10 additions & 0 deletions chai-dom.js
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
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 631d720

Please sign in to comment.