From 9c9bb3d4cad4d5928a8a84fa5e683379959e65b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patryk=20Lizon=CC=81?= Date: Mon, 13 Sep 2021 13:24:13 +0200 Subject: [PATCH] Add 'focus' assertion --- README.md | 9 +++++++++ chai-dom.js | 15 +++++++++++++++ test/tests.js | 38 +++++++++++++++++++++++++++++++++++++- 3 files changed, 61 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c0a9379..6f6a6c7 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/chai-dom.js b/chai-dom.js index 2a57414..d24c88a 100644 --- a/chai-dom.js +++ b/chai-dom.js @@ -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 + ) + + } + }) })); diff --git a/test/tests.js b/test/tests.js index 3455210..b38926c 100644 --- a/test/tests.js +++ b/test/tests.js @@ -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 @@ -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(''); + var blurred = parse(''); + + 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"); + }); + }) })