feat(renderer-test): allow specifying indent for serialization

This commit is contained in:
Evan You 2018-10-01 17:35:55 -04:00
parent 21e8798a21
commit 4f6531aa3c
2 changed files with 21 additions and 10 deletions

View File

@ -138,8 +138,8 @@ describe('test renderer', () => {
}
const root = nodeOps.createElement('div')
render(h(App), root)
expect(serialize(root)).toEqual(
expect(serialize(root)).toEqual(`<div><div id="test">hello</div></div>`)
expect(serialize(root, 2)).toEqual(
`<div>
<div id="test">
hello

View File

@ -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
}