Skip to content

Commit

Permalink
Added support for 'to have no children' HTMLElement assertion
Browse files Browse the repository at this point in the history
  • Loading branch information
Munter committed Mar 5, 2015
1 parent 78bc09d commit c708ca0
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ module.exports = {
}
});

expect.addAssertion('HTMLElement', ['to [only] have (attribute|attributes)'], function (expect, subject, cmp) {
expect.addAssertion('HTMLElement', 'to [only] have (attribute|attributes)', function (expect, subject, cmp) {
var attrs = getAttributes(subject);

if (typeof cmp === 'string') {
Expand All @@ -127,5 +127,15 @@ module.exports = {
expect(attrs, 'to [exhaustively] satisfy', cmp);
}
});

expect.addAssertion('HTMLElement', 'to have [no] (child|children)', function (expect, subject, query, cmp) {
if (this.flags.no) {
this.errorMode = 'nested';
return expect(Array.prototype.slice.call(subject.childNodes), 'to be an empty array');
} else {
var children = Array.prototype.slice.call(subject.querySelectorAll(query));
throw children;
}
});
}
};
38 changes: 38 additions & 0 deletions test/unexpected-dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,42 @@ describe('unexpected-dom', function () {
});
});

describe('to have children', function () {
describe('with no children flag', function () {
it('should match element with no children', function () {
this.body.innerHTML = '<div></div>';
var el = this.body.firstChild;

expect(el, 'to have no children');
});

it('should fail on element with HTMLElement children', function () {
this.body.innerHTML = '<div><p></p></div>';
var el = this.body.firstChild;

expect(function () {
expect(el, 'to have no children');
}, 'to throw', /^expected <div >...<\/div> to have no children/);
});

it('should fail on element with HTMLComment children', function () {
this.body.innerHTML = '<div><!-- Comment --></div>';
var el = this.body.firstChild;

expect(function () {
expect(el, 'to have no children');
}, 'to throw', /^expected <div \/> to have no children/);
});

it('should fail on element with TextNode children', function () {
this.body.innerHTML = '<div>I am a text</div>';
var el = this.body.firstChild;

expect(function () {
expect(el, 'to have no children');
}, 'to throw', /^expected <div \/> to have no children/);
});
});
});

});

0 comments on commit c708ca0

Please sign in to comment.