Skip to content

Commit

Permalink
Merge pull request #53 from patricklizon/master
Browse files Browse the repository at this point in the history
Add 'focus' assertion
  • Loading branch information
nathanboktae committed Sep 14, 2021
2 parents 0d3910f + ae3a47d commit 62fc82c
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,15 @@ document.querySelector('.container').should.have.style('color', 'rgb(55, 66, 77)
expect(document.querySelector('.container')).not.to.have.style('borderWidth', '3px')
```

### `focus`

Assert that the [HTMLElement][] has set focus.

```js
document.querySelector('input').should.have.focus
expect(document.querySelector('.container')).not.to.have.focus
```

## Installation

### npm
Expand Down
15 changes: 15 additions & 0 deletions chai-dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -386,4 +386,19 @@
, actual
)
})

chai.Assertion.overwriteProperty('focus', function() {
return function () {
var el = flag(this, 'object'), actual = el.ownerDocument.activeElement

this.assert(
el === el.ownerDocument.activeElement
, 'expected #{this} to have focus'
, 'expected #{this} not to have focus'
, el
, actual
)

}
})
}));
37 changes: 37 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -998,4 +998,41 @@ describe('DOM assertions', function() {
.should.equal('p#nlt1, p#nlt2, p#nlt3, p#nlt4, p#nlt5... (+3 more)')
})
})

describe('focus', function() {
var container = document.getElementById("mocha");
var focused = parse('<input type="text" id="focused" name="focused">');
var blurred = parse('<input type="text" id="blurred" name="blurred">');

beforeEach(function() {
container.appendChild(focused)
container.appendChild(blurred)
focused.focus();
});

afterEach(function() {
container.removeChild(focused)
container.removeChild(blurred)
});

it("passes when the element has focus", function(){
focused.should.have.focus;
});

it("passes negated when the element does not have focus", function(){
blurred.should.not.have.focus;
});

it("fails when the element does not have focus", function(){
(function(){
blurred.should.have.focus;
}).should.fail("expected " + inspect(blurred) + " to have focus");
});

it("fails negated when element has focus", function(){
(function(){
focused.should.not.have.focus;
}).should.fail("expected " + inspect(focused) + " not to have focus");
});
})
})

0 comments on commit 62fc82c

Please sign in to comment.