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 >
) ;
} ;