Skip to content

Commit c708ca0

Browse files
committed
Added support for 'to have no children' HTMLElement assertion
1 parent 78bc09d commit c708ca0

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

lib/index.js

+11-1
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ module.exports = {
114114
}
115115
});
116116

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

120120
if (typeof cmp === 'string') {
@@ -127,5 +127,15 @@ module.exports = {
127127
expect(attrs, 'to [exhaustively] satisfy', cmp);
128128
}
129129
});
130+
131+
expect.addAssertion('HTMLElement', 'to have [no] (child|children)', function (expect, subject, query, cmp) {
132+
if (this.flags.no) {
133+
this.errorMode = 'nested';
134+
return expect(Array.prototype.slice.call(subject.childNodes), 'to be an empty array');
135+
} else {
136+
var children = Array.prototype.slice.call(subject.querySelectorAll(query));
137+
throw children;
138+
}
139+
});
130140
}
131141
};

test/unexpected-dom.js

+38
Original file line numberDiff line numberDiff line change
@@ -157,4 +157,42 @@ describe('unexpected-dom', function () {
157157
});
158158
});
159159

160+
describe('to have children', function () {
161+
describe('with no children flag', function () {
162+
it('should match element with no children', function () {
163+
this.body.innerHTML = '<div></div>';
164+
var el = this.body.firstChild;
165+
166+
expect(el, 'to have no children');
167+
});
168+
169+
it('should fail on element with HTMLElement children', function () {
170+
this.body.innerHTML = '<div><p></p></div>';
171+
var el = this.body.firstChild;
172+
173+
expect(function () {
174+
expect(el, 'to have no children');
175+
}, 'to throw', /^expected <div >...<\/div> to have no children/);
176+
});
177+
178+
it('should fail on element with HTMLComment children', function () {
179+
this.body.innerHTML = '<div><!-- Comment --></div>';
180+
var el = this.body.firstChild;
181+
182+
expect(function () {
183+
expect(el, 'to have no children');
184+
}, 'to throw', /^expected <div \/> to have no children/);
185+
});
186+
187+
it('should fail on element with TextNode children', function () {
188+
this.body.innerHTML = '<div>I am a text</div>';
189+
var el = this.body.firstChild;
190+
191+
expect(function () {
192+
expect(el, 'to have no children');
193+
}, 'to throw', /^expected <div \/> to have no children/);
194+
});
195+
});
196+
});
197+
160198
});

0 commit comments

Comments
 (0)