首页 > 解决方案 > 访问使用 JSDOM 创建的条形图的属性

问题描述

我正在学习 jsdom 以测试 node.js 中的可视化,但在访问使用 jsdom 创建的对象的属性时遇到了麻烦。也许你能帮助我?

test.js:(这是我创建应该测试的 barChart 的类)

let jsdom 

try {
  jsdom = require('jsdom/lib/old-api.js'); // jsdom >= 10.x
} catch (e) {
  jsdom = require('jsdom'); // jsdom <= 9.x
}

// wrapped in jsdom:
exports.barChart = function () {

 let barProperties;

  let bar = jsdom.env(
    '<html><body></body></html>', ['http://d3js.org/d3.v3.min.js'],
    function (err, window) {
      let svg = window.d3.select('body').append('svg')
        .attr('height', '500')
        .attr('width', '500')

      svg.append('rect')
        .attr('x', 10)
        .attr('y', 10)
        .attr('width', 80)
        .attr('height', 80)
        .style('fill', 'orange')

      barProperties = window.d3.select('body').html();
      console.log(barProperties);
    }
  )
  return bar;
}

barProperties 产生输出:

<script class="jsdom" src="http://d3js.org/d3.v3.min.js"></script>
<svg height="500" width="500">
    <rect x="10" y="10" width="80" height="80" style="fill: orange;"></rect>
</svg>

test-spec.js:(这里我想从 barProperties 访问 svg 的“height”属性)

let test = require('../../javascripts/test')
let jsdom

try {
  jsdom = require('jsdom/lib/old-api.js'); // jsdom >= 10.x
} catch (e) {
  jsdom = require('jsdom'); // jsdom <= 9.x
}

describe('Test d3 with jasmine', function () {

  describe('the svg', function () {

    it('should be created', function () {
      expect(getSvg().attr('height')).toBe('500'); <--- this doesn't work
    });
  });

  function getSvg () {

    test.barChart();
  }
})

错误信息:

TypeError: Cannot read property 'attr' of undefined

那么有没有办法从 barProperties 导出 jsdom 窗口对象呢?太感谢了!

标签: node.jsjasminejsdom

解决方案


推荐阅读