|
| 1 | +import { expect } from "chai"; |
| 2 | +import { Box, SomeNode, SomeNodeInPackage } from "../nodes"; |
| 3 | + |
| 4 | +describe('Node.transformChildren', () => { |
| 5 | + let childNode1: SomeNode; |
| 6 | + let childNode2: SomeNode; |
| 7 | + let boxNode: Box; |
| 8 | + |
| 9 | + beforeEach(() => { |
| 10 | + childNode1 = new SomeNode("Child1"); |
| 11 | + childNode2 = new SomeNode("Child2"); |
| 12 | + |
| 13 | + boxNode = new Box("BoxNode", [childNode1, childNode2]); |
| 14 | + }) |
| 15 | + |
| 16 | + it('should apply in-place transformation to each child node', () => { |
| 17 | + const inPlaceTransformation = (node: SomeNode): SomeNode => { |
| 18 | + node.a = node.a?.toUpperCase(); |
| 19 | + return node; |
| 20 | + }; |
| 21 | + |
| 22 | + boxNode.transformChildren(inPlaceTransformation); |
| 23 | + |
| 24 | + expect(boxNode.contents[0]["a"]).to.eq("CHILD1"); |
| 25 | + expect(boxNode.contents[0]).to.eq(childNode1); |
| 26 | + expect(boxNode.contents[1]["a"]).to.eq("CHILD2"); |
| 27 | + expect(boxNode.contents[1]).to.eq(childNode2); |
| 28 | + }); |
| 29 | + |
| 30 | + it('should replace children nodes when used with pure-functions', () => { |
| 31 | + const replaceTransformation = (node: SomeNode): SomeNode => { |
| 32 | + return new SomeNode(node.a?.toUpperCase()) |
| 33 | + }; |
| 34 | + |
| 35 | + boxNode.transformChildren(replaceTransformation); |
| 36 | + |
| 37 | + expect(boxNode.contents[0]["a"]).to.eq("CHILD1"); |
| 38 | + expect(boxNode.contents[0]).to.not.eq(childNode1); |
| 39 | + expect(boxNode.contents[1]["a"]).to.eq("CHILD2"); |
| 40 | + expect(boxNode.contents[1]).to.not.eq(childNode2); |
| 41 | + }); |
| 42 | +}); |
| 43 | + |
| 44 | +describe('Node.replaceWith', () => { |
| 45 | + it('should replace a child node with another node', () => { |
| 46 | + const childNode1 = new SomeNode("Child1"); |
| 47 | + const childNode2 = new SomeNode("Child2"); |
| 48 | + |
| 49 | + const parentNode = new SomeNodeInPackage("ParentNode"); |
| 50 | + |
| 51 | + parentNode.setChild('someNode', childNode1); |
| 52 | + expect(parentNode.getChildren('someNode')).to.eql([childNode1]); |
| 53 | + childNode1.replaceWith(childNode2); |
| 54 | + expect(parentNode.getChildren('someNode')).to.eql([childNode2]); |
| 55 | + }); |
| 56 | + |
| 57 | + it('should throw error if parent is not set', () => { |
| 58 | + const childNode1 = new SomeNode("Child1"); |
| 59 | + |
| 60 | + const nodeWithoutParent = new SomeNode("NodeWithoutParent"); |
| 61 | + expect(() => nodeWithoutParent.replaceWith(childNode1)).to.throw('Cannot replace a Node that has no parent'); |
| 62 | + }); |
| 63 | +}); |
| 64 | + |
0 commit comments