From 4f6531aa3c41193f190c5e35d404bdeca5b1d1e9 Mon Sep 17 00:00:00 2001 From: Evan You Date: Mon, 1 Oct 2018 17:35:55 -0400 Subject: [PATCH] feat(renderer-test): allow specifying indent for serialization --- .../__tests__/testRenderer.spec.ts | 4 +-- packages/renderer-test/src/serialize.ts | 27 +++++++++++++------ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/packages/renderer-test/__tests__/testRenderer.spec.ts b/packages/renderer-test/__tests__/testRenderer.spec.ts index e50f9706..f20777a0 100644 --- a/packages/renderer-test/__tests__/testRenderer.spec.ts +++ b/packages/renderer-test/__tests__/testRenderer.spec.ts @@ -138,8 +138,8 @@ describe('test renderer', () => { } const root = nodeOps.createElement('div') render(h(App), root) - - expect(serialize(root)).toEqual( + expect(serialize(root)).toEqual(`
hello
`) + expect(serialize(root, 2)).toEqual( `
hello diff --git a/packages/renderer-test/src/serialize.ts b/packages/renderer-test/src/serialize.ts index ffb81f04..ee75b87e 100644 --- a/packages/renderer-test/src/serialize.ts +++ b/packages/renderer-test/src/serialize.ts @@ -1,23 +1,33 @@ import { TestElement, TestNode, NodeTypes, TestText } from './nodeOps' -export function serialize(node: TestNode, depth: number = 0): string { +export function serialize( + node: TestNode, + indent: number = 0, + depth: number = 0 +): string { if (node.type === NodeTypes.ELEMENT) { - return serializeElement(node, depth) + return serializeElement(node, indent, depth) } else { - return serializeText(node, depth) + return serializeText(node, indent, depth) } } -function serializeElement(node: TestElement, depth: number): string { +function serializeElement( + node: TestElement, + indent: number, + depth: number +): string { const props = Object.keys(node.props) .map(key => { return `${key}=${JSON.stringify(node.props[key])}` }) .join(' ') const children = node.children.length - ? `\n${node.children.map(c => serialize(c, depth + 1))}\n` + ? (indent ? `\n` : ``) + + node.children.map(c => serialize(c, indent, depth + 1)) + + (indent ? `\n` : ``) : `` - const padding = ` `.repeat(depth) + const padding = indent ? ` `.repeat(indent).repeat(depth) : `` return ( `${padding}<${node.tag}${props ? ` ${props}` : ``}>` + `${children}` + @@ -25,6 +35,7 @@ function serializeElement(node: TestElement, depth: number): string { ) } -function serializeText(node: TestText, depth: number): string { - return ` `.repeat(depth) + node.text +function serializeText(node: TestText, indent: number, depth: number): string { + const padding = indent ? ` `.repeat(indent).repeat(depth) : `` + return padding + node.text }