feat(renderer-test): allow specifying indent for serialization
This commit is contained in:
parent
21e8798a21
commit
4f6531aa3c
@ -138,8 +138,8 @@ describe('test renderer', () => {
|
|||||||
}
|
}
|
||||||
const root = nodeOps.createElement('div')
|
const root = nodeOps.createElement('div')
|
||||||
render(h(App), root)
|
render(h(App), root)
|
||||||
|
expect(serialize(root)).toEqual(`<div><div id="test">hello</div></div>`)
|
||||||
expect(serialize(root)).toEqual(
|
expect(serialize(root, 2)).toEqual(
|
||||||
`<div>
|
`<div>
|
||||||
<div id="test">
|
<div id="test">
|
||||||
hello
|
hello
|
||||||
|
@ -1,23 +1,33 @@
|
|||||||
import { TestElement, TestNode, NodeTypes, TestText } from './nodeOps'
|
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) {
|
if (node.type === NodeTypes.ELEMENT) {
|
||||||
return serializeElement(node, depth)
|
return serializeElement(node, indent, depth)
|
||||||
} else {
|
} 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)
|
const props = Object.keys(node.props)
|
||||||
.map(key => {
|
.map(key => {
|
||||||
return `${key}=${JSON.stringify(node.props[key])}`
|
return `${key}=${JSON.stringify(node.props[key])}`
|
||||||
})
|
})
|
||||||
.join(' ')
|
.join(' ')
|
||||||
const children = node.children.length
|
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 (
|
return (
|
||||||
`${padding}<${node.tag}${props ? ` ${props}` : ``}>` +
|
`${padding}<${node.tag}${props ? ` ${props}` : ``}>` +
|
||||||
`${children}` +
|
`${children}` +
|
||||||
@ -25,6 +35,7 @@ function serializeElement(node: TestElement, depth: number): string {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function serializeText(node: TestText, depth: number): string {
|
function serializeText(node: TestText, indent: number, depth: number): string {
|
||||||
return ` `.repeat(depth) + node.text
|
const padding = indent ? ` `.repeat(indent).repeat(depth) : ``
|
||||||
|
return padding + node.text
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user