import { setupScratch, teardown, serializeHtml } from '../../../test/_util/helpers'; import { div, span } from '../../../test/_util/dom'; import React, { createElement, Children, render } from 'preact/compat'; describe('Children', () => { /** @type {HTMLDivElement} */ let scratch; beforeEach(() => { scratch = setupScratch(); }); afterEach(() => { teardown(scratch); }); describe('.count', () => { let count; function Foo(props) { count = Children.count(props.children); return
{count}
; } it('should return 0 for no children', () => { render(, scratch); expect(count).to.equal(0); }); it('should return number of children', () => { render(
foo , scratch ); expect(count).to.equal(2); }); }); describe('.only', () => { let actual; function Foo(props) { actual = Children.only(props.children); return
{actual}
; } it('should only allow 1 child', () => { render(foo, scratch); expect(actual).to.equal('foo'); }); it('should throw if no children are passed', () => { // eslint-disable-next-line prefer-arrow-callback expect(function() { render(, scratch); }).to.throw(); }); it('should throw if more children are passed', () => { // eslint-disable-next-line prefer-arrow-callback expect(function() { render( foo , scratch ); }).to.throw(); }); }); describe('.map', () => { function Foo(props) { let children = Children.map(props.children, child => ( {child} )); return
{children}
; } it('should iterate over children', () => { render( foo
bar
, scratch ); let expected = div([span('foo'), span(div('bar'))]); expect(serializeHtml(scratch)).to.equal(expected); }); it('should work with no children', () => { render(, scratch); expect(serializeHtml(scratch)).to.equal('
'); }); it('should work with children as zero number', () => { const testNumber = 0; render({testNumber}, scratch); expect(serializeHtml(scratch)).to.equal('
0
'); }); it('should flatten result', () => { const ProblemChild = ({ children }) => { return React.Children.map(children, child => { return React.Children.map(child.props.children, x => x); }).filter(React.isValidElement); }; const App = () => { return (
1
2
); }; render(, scratch); expect(scratch.textContent).to.equal('12'); }); it('should call with indices', () => { const assertion = []; const ProblemChild = ({ children }) => { return React.Children.map(children, (child, i) => { assertion.push(i); return React.Children.map(child.props.children, (x, j) => { assertion.push(j); return x; }); }).filter(React.isValidElement); }; const App = () => { return (
1
2
3
4
); }; render(, scratch); expect(scratch.textContent).to.equal('1234'); expect(assertion.length).to.equal(6); }); }); describe('.forEach', () => { function Foo(props) { let children = []; Children.forEach(props.children, child => children.push({child}) ); return
{children}
; } it('should iterate over children', () => { render( foo
bar
, scratch ); let expected = div([span('foo'), span(div('bar'))]); expect(serializeHtml(scratch)).to.equal(expected); }); }); });