小编Kre*_*eha的帖子

有没有办法模拟 SVGTextElement 以便能够使用 Jest 测试函数,该函数使用 getBBox() 来测量文本?

在决定应该使用什么字体大小之前,我编写了简单的函数来测量文本。

const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
svg.appendChild(text);

interface HeightAndWidth {
  width: number;
  height: number;
}

interface MeasureProps {
  label: string;
  fontFamily: string;
  size: number;
  fontWeight?: number;
  lineHeight?: number;
  letterSpacing?: string;
}

export const measureText = ({
  label,
  fontFamily,
  size,
  fontWeight = 400,
  lineHeight = 1,
  letterSpacing = '0',
}: MeasureProps): HeightAndWidth => {
  text.setAttribute('font-size', `${size}px`);
  text.setAttribute('line-height', `${lineHeight}px`);
  text.setAttribute('font-family', fontFamily);
  text.setAttribute('font-weight', `${fontWeight}`);
  text.setAttribute('letter-spacing', letterSpacing);
  text.textContent = label;
  document.body.appendChild(svg);

  const { width, height } = text.getBBox();

  return …
Run Code Online (Sandbox Code Playgroud)

javascript svg typescript jestjs

5
推荐指数
1
解决办法
686
查看次数

标签 统计

javascript ×1

jestjs ×1

svg ×1

typescript ×1