chromium/third_party/blink/web_tests/svg/text/text-rect-precision.html

<!DOCTYPE html>
<title>The width of text element is similar to the sum of the width of all characters.</title>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<svg style="position: absolute; top: 10px; left: 10px; width: 500px; height: 300px;">
    <g>
        <text id="test" x="0" y="50" font-size="25" fill="#000" text-rendering="geometricPrecision">Sphinx of black quartz, judge my vow.</text>
    </g>
    <g>
        <text id="measure" x="0" y="150" fill="#000" text-rendering="geometricPrecision" xml:space="preserve">&nbsp;</text>
    </g>
</svg>
<script>
function measureText(testElement) {
  var measureElement = document.getElementById('measure');
  measureElement.setAttribute('font-size', testElement.getAttribute('font-size'));
  var str = testElement.firstChild.nodeValue;

  var characterWidths = {};
  var width = 0;
  for (var i = 0; i < str.length; i++) {
      var c = str[i];
      var w = characterWidths[c];
      if (!w) {
          measureElement.firstChild.nodeValue = c;
          w = measureElement.getBoundingClientRect().width;
          characterWidths[c] = w;
      }
      width += w;
  }
  return width;
}

test(function() {
  var element = document.getElementById('test');
  var elementWidth = element.getBoundingClientRect().width;
  var textWidth = measureText(element);
  // This tolerance value is made up but our goal is to ensure that the
  // sum of individual glyph widths is roughly similar to the total element
  // width.
  var glyphOverflowTolerance = Math.min(elementWidth, textWidth) / 2;
  // The sum of individual character widths will include the glyph
  // overflow of each character separately and therefore the total element
  // width should be smaller.
  assert_less_than_equal(elementWidth, textWidth);
  assert_less_than_equal(Math.abs(elementWidth - textWidth), glyphOverflowTolerance);
});
</script>