dom serializer
v0.6.3
将完整的DOM结构(包括阴影DOM)插入字符串的标记序列化器。该库可用为:
renderToString()
函数,将@quatico/dom-serializer
添加为(dev-)依赖项
pnpm add -D @quatico/dom-serializer
您可以将库用作Jest快照测试的序列化器。将其添加到jest.config.js
中的snapshotSerializers
中:
// jest.config.js
module . exports = {
/* ... */
snapshotSerializers : [ "@quatico/dom-serializer/bin/serializer" ] ,
}
在玩笑测试中致电toMatchSnapshot()
或toMatchInlineSnapshot()
创建/比较快照:
describe ( "my-element" , ( ) => {
it ( `shows markup with default properties` , async ( ) => {
const el : HTMLElement = ... ;
expect ( el ) . toMatchSnapshot ( ) ;
} ) ;
...
您可以将软件包用作库。创建以下结构的脚本文件,并使用module.exports
导入DomSerializer
语句:
// ./tests/customSnapshotSerializer.ts
import { DomSerializer } from "@quatico/dom-serializer" ;
module . exports = new DomSerializer ( { filterTags : [ "script" ] } ) ;
将您的customSnapshotSerializer.ts
添加到Jest.config.js:
// jest.config.js
module . exports = {
/* ... */
snapshotSerializers : [ "./tests/customSnapshotSerializer.ts" ] ,
}
类DomSerializer提供以下RenderOptions
来自定义快照:
diffable
:布尔值以增加额外的线路休息,以提高可比性;默认为true。filterAttrs
:从快照中滤除的小写属性名称的数组;默认为[]。filterComments
:标志以滤除快照中的HTML注释;默认为true。filterTags
:从快照中滤除的小写标签名称的数组;默认为[“样式”,“脚本”]。indent
:产生结构的初始缩进字符串;默认为空字符串。儿童级别由4个空间缩进。shadow
:布尔值启用/禁用阴影dom内容的渲染;默认为true。shadowDepth
:要渲染的表演根数;默认为无限。shadowRoots
:控制阴影根的渲染方式。默认为“声明性”。slottedContent
:控制开槽内容的渲染方式。将其显示为引用的孩子或复制到插槽元素。默认为“忽略”。 您还可以使用库将DOM结构渲染到字符串中:
import { renderToString } from "@quatico/dom-serializer" ;
const htmlElement = ... ;
const string = renderToString ( htmlElement , {
diffable : true ,
filterAttrs : [ "id" ] ,
filterComments : true ,
filterTags : [ "style" , "script" ] ,
shadow : true ,
shadowDepth : 1 ,
shadowRoots : "declarative" ,
} ) ;
在这里,与DomSerializer
相同的RenderOptions
可用于自定义生成的字符串。
使用库可以轻松地创建一个反应组件,该组件在Storybook中显示提供的元素的DOM结构:
import { renderToString } from "@quatico/dom-serializer" ;
import { Source } from "@storybook/components" ;
import * as React from "react" ;
import { useEffect , useRef , useState } from "react" ;
export const DomMarkup = ( { children , shadow , shadowDepth = 1 , diffable = false } : any ) => {
const domRef = useRef < HTMLDivElement > ( null ) ;
const [ markup , setMarkup ] = useState ( "" ) ;
useEffect ( ( ) => {
const host = domRef . current ;
setMarkup (
host ?. firstElementChild ? renderToString ( host . firstElementChild , { diffable , shadow , shadowDepth } ) : ""
) ;
} ) ;
return (
< div >
< div ref = { domRef } style = { { display : "none" } } className = { "dom-markup__dom-container" } >
{ children }
< / div >
< div className = { "dom-markup__markup-container" } >
< Source language = { "html" } format = { false } code = { markup } / >
< / div >
< / div >
) ;
} ;