Skip to content

Commit

Permalink
Add 'focus' assertion
Browse files Browse the repository at this point in the history
  • Loading branch information
patricklizon committed Sep 13, 2021
1 parent 0d3910f commit 9c9bb3d
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
9 changes: 9 additions & 0 deletions README.md
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
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
)

}
})
}));
38 changes: 37 additions & 1 deletion test/tests.js
Expand Up @@ -897,7 +897,6 @@ describe('DOM assertions', function() {
hiddenViaCSS.should.not.be.visible
collapsedViaCSS.should.not.be.visible
})

it('fails when the element has visibility: hidden', function() {
(function() {
hiddenViaStyle.should.be.visible
Expand Down Expand Up @@ -998,4 +997,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 9c9bb3d

Please sign in to comment.