【问题标题】:Trouble testing an SVG object in Jasmine在 Jasmine 中测试 SVG 对象时遇到问题
【发布时间】:2017-04-09 03:10:33
【问题描述】:

我在我的测试中无法复制 SVG 功能。 Jasmine 在 Sinatra 网络应用程序中与 jasmine-jquery 成功连接。这些测试适用于与 SVG 对象关联的 JavaScript 函数。如:

function findMapImage() {
  return $("#svg")[0].contentDocument;
}

function findRegions(map) {
  return map.querySelectorAll('path');
}

Jasmine 灯具看起来像这样(我已经去掉了一些细节):

<object id="svg" type="image/svg+xml">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 484.33 547" height="500">
    <path/>
    <path/>
  </svg>
</object>

我在测试中添加了以下几行:

var map = findMapImage();
console.log(map)

console.log 产生:

#document
  <html>
    #shadow-root (open)
      <shadow>
        <head>
        <body>
      </shadow>
    <head></head>
    <body></body>
  <html>

但我应该看到的更像是:

#document
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 484.33 547" height="500">
    <defs>...</defs>
    <title>...</title>
    <path></path>
    etc.
  </svg>

我已经read 认为“image/svg+xml”类型的 svg 对象需要“xmlns”资源。所以我最好的猜测是 xmlns 资源没有加载。所以也许我需要弄清楚如何加载远程资源或在本地下载它?我对其他想法持开放态度。

【问题讨论】:

  • 在您的 HTML 中直接使用 &lt;object&gt; 元素是否适合您的用例?
  • 不知道为什么。刚刚试了一下,并在 标签中移动了 id "svg"。它产生未定义的。
  • 使用纯内联&lt;svg&gt; 标签,您可以从findMapImage 中删除.contentDocument,直接使用该元素。
  • 你死定了。我想这确实会扭曲我的用例。在我的测试和这个夹具之外,我的 svg 没有内联加载。我只是将它内联,因为我不确定如何为 jasmine 提供通往我的资源的路径。
  • 也就是说,既然我可以访问 svg,我想我可以避免测试 findMapImage 并专注于其他人

标签: javascript svg jasmine jasmine-jquery


【解决方案1】:

假设您的 svg 的宽度和高度为 500px,那么它可以是:

describe('the svg' ,function() {

   it('should be created', function() {
      expect(findMapImage()).not.toBeNull();
    });

    it('should have the correct height', function() {
     expect(findMapImage().attr('height')).toBe('500');
     });

   // you can use this if you have width, just in case
    it('should have the correct width', function() {
      expect(findMapImage().attr('width')).toBe('500');
     }); 

    function findMapImage() {
      return $("#svg")[0].contentDocument;
    }

});

【讨论】:

  • 您好,感谢您的回答,但这并不是我要问的。我知道如何写一个“它块”。但我实际上并没有使用 SVG。我添加了一个编辑来强调这个问题。
  • 如果你console.log($("#svg")),你会得到什么?
  • 它返回 [function] 并且 $("#svg")[0] 返回函数 anonymous()。我担心的是我们正在更改我的功能而不是对其进行测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
相关资源
最近更新 更多