Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 244
RuntimeError Avatar asked Oct 16 '25 01:10

RuntimeError


1 Answers

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.

like image 146
Sirko Avatar answered Oct 18 '25 13:10

Sirko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!