简体   繁体   中英

Testing d3 with Node.js, JSDOM and Jasmine

I'd like to test if a simple bar chart is rendered in my node.js/d3 application using jasmine. I am a beginner with Javascript and especially node.js, so hopefully you have an idea what I should do.

test.js (file that should be tested) :

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 (here the test is executed) :

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');
  }
})

Without JSDOM, an error occurs in this line:

return d3.select('svg');

... and here it is:

   Message:
   ReferenceError: document is not defined

From my researches in the web I learned that this error occurs because node.js does not provide a DOM by default. Therefore, the DOM has to be emulated using JSDOM.

Unfortunately, I have absolutely no clue where to start. So my question is: How can I use JSDOM to render the barChart, so that the Jasmine test will be able to execute? Furthermore, I'm not sure if the usage of "require" and "exports" is correct.

The basis of my approach is this guide: http://busypeoples.github.io/post/testing-d3-with-jasmine/

Thank you so much!

I've done something similar in the past and try to list the relevant parts of my code as follows:

// 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' )
/* ... */

It was important to start with d3.select( document ) to make d3 aware of the (emulated) DOM tree. Otherwise, I got errors like yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM