【问题标题】:Testing d3 with Node.js, JSDOM and Jasmine使用 Node.js、JSDOM 和 Jasmine 测试 d3
【发布时间】:2018-07-12 13:41:42
【问题描述】:

我想测试是否使用 jasmine 在我的 node.js/d3 应用程序中呈现了一个简单的条形图。我是 Javascript 尤其是 node.js 的初学者,所以希望你知道我应该做什么。

test.js(应测试的文件)

var d3 = require('d3');

exports.barChart = function() {
  var that = {};

  that.render = function() {
    var svg = d3.select('body').append('svg')
      .attr('height', '500')
      .attr('width', '500')
      .append('g')
      .attr("transform", "translate(0, 0)");
  };

  return that;
}

test-spec.js(此处执行测试)

var test = require('../javascripts/test');
var d3 = require('d3');

var jsdom = require("jsdom");  
const { JSDOM } = jsdom; // <--- how is jsdom used?

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

  describe('the svg', function () {

    beforeEach(function() {
      var bar = test.barChart();
      //bar.render();
    });

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

  function getSvg() {
    return d3.select('svg');
  }
})

没有JSDOM,这行报错:

return d3.select('svg');

...这里是:

   Message:
   ReferenceError: document is not defined

从我在网络上的研究中,我了解到这个错误的发生是因为 node.js 默认不提供 DOM。因此,必须使用 JSDOM 来模拟 DOM。

不幸的是,我完全不知道从哪里开始。所以我的问题是:如何使用 JSDOM 来渲染 barChart,以便 Jasmine 测试能够执行?此外,我不确定“require”和“exports”的使用是否正确。

我的方法的基础是本指南:http://busypeoples.github.io/post/testing-d3-with-jasmine/

非常感谢!

【问题讨论】:

  • 您提到的指南并未在 Node 环境中运行测试。它使用 Karma 运行它们,即测试本身在浏览器中进行评估。除非你知道自己在做什么,否则我建议不要接触 JSDOM,而是使用真正的 DOM。

标签: javascript node.js d3.js jasmine


【解决方案1】:

我过去做过类似的事情,并尝试将我的代码的相关部分列出如下:

// load the jsdom constructor and d3
const JSDOM = require( 'jsdom' ).JSDOM,
      d3    = require( 'd3' );

// initialize a new document
// wrapper is a generic HTML document serving as the base (not sure, if it is needed in your case)
const jsdom = new JSDOM( wrapper, { runScripts: "outside-only" } );

// get a reference of the document object
const document = jsdom.window.document;

// start with the visualization
d3.select( document )
  .select( 'svg' )
/* ... */

d3.select( document ) 开始让 d3 了解(模拟的)DOM 树很重要。否则,我会遇到像你这样的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    相关资源
    最近更新 更多