Skip to content

Commit

Permalink
[Fix] shallow: .equals(): flatten children when comparing
Browse files Browse the repository at this point in the history
Fixes #1347
  • Loading branch information
ljharb committed Jul 7, 2018
1 parent ee180af commit 18de4ed
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
29 changes: 29 additions & 0 deletions packages/enzyme-test-suite/test/ShallowWrapper-spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,35 @@ describe('shallow', () => {
expect(shallow(<Foo />).equals(<Foo />)).to.equal(false);
});
});

it('flattens arrays of children to compare', () => {
class TwoChildren extends React.Component {
render() {
return (
<div className="parent-component-class">
<div key="a" className="asd" />
<div key="b" className="fgh" />
</div>
);
}
}

class TwoChildrenOneArrayed extends React.Component {
render() {
return (
<div className="parent-component-class">
<div key="a" className="asd" />
{[<div key="b" className="fgh" />]}
</div>
);
}
}
const twoChildren = shallow(<TwoChildren />);
const twoChildrenOneArrayed = shallow(<TwoChildrenOneArrayed />);

expect(twoChildren.equals(twoChildrenOneArrayed.getElement())).to.equal(true);
expect(twoChildrenOneArrayed.equals(twoChildren.getElement())).to.equal(true);
});
});

describe('.hostNodes()', () => {
Expand Down
1 change: 1 addition & 0 deletions packages/enzyme/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"author": "Leland Richardson <[email protected]>",
"license": "MIT",
"dependencies": {
"array.prototype.flat": "^1.2.1",
"cheerio": "^1.0.0-rc.2",
"function.prototype.name": "^1.0.3",
"has": "^1.0.1",
Expand Down
13 changes: 8 additions & 5 deletions packages/enzyme/src/Utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import is from 'object-is';
import entries from 'object.entries';
import functionName from 'function.prototype.name';
import has from 'has';
import flat from 'array.prototype.flat';

import configuration from './configuration';
import validateAdapter from './validateAdapter';
import { childrenOfNode } from './RSTTraversal';
Expand Down Expand Up @@ -72,11 +74,12 @@ function internalChildrenCompare(a, b, lenComp, isLoose) {
if (!Array.isArray(a) && !Array.isArray(b)) {
return nodeCompare(a, b, lenComp);
}
if (!a && !b) return true;
if (a.length !== b.length) return false;
if (a.length === 0 && b.length === 0) return true;
for (let i = 0; i < a.length; i += 1) {
if (!nodeCompare(a[i], b[i], lenComp)) return false;
const flatA = flat(a, Infinity);
const flatB = flat(b, Infinity);
if (flatA.length !== flatB.length) return false;
if (flatA.length === 0 && flatB.length === 0) return true;
for (let i = 0; i < flatA.length; i += 1) {
if (!nodeCompare(flatA[i], flatB[i], lenComp)) return false;
}
return true;
}
Expand Down

0 comments on commit 18de4ed

Please sign in to comment.