score:2

Accepted answer

it seems you have a dependency version issue - the code in the github project is several years old and the instructions are loading much later versions of the dependencies than when the example code was written.

i get an npm error trying to install d3js and jsdom is on v16.4. if i run:

npm install jsdom d3 --save

my package.json is:

{
  "name": "test-jsdom",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "isc",
  "dependencies": {
    "d3": "^6.5.0",
    "jsdom": "^16.4.0"
  }
}

github user dam1r89 shows a way to do what you are trying on later versions in this gist.

my take on it:

const d3 = require("d3");
const fs = require("fs");
const {jsdom} = require("jsdom");

// init d3 - https://gist.github.com/tomgp/c99a699587b5c5465228
const minhtml = "<html><head></head><body></body></html>";
const dom = new jsdom(`${minhtml}`, { pretendtobevisual: true });
const window = dom.window;
window.d3 = d3.select(window.document); 

// d3js code * * * * * * * * * * * * * * * * * * * * * * * *
var svg = window.d3.select("body")
  .append("svg")
  .attr("width", 100)
  .attr("height", 100);

svg.append("rect")
  .attr("id", "rect1")
  .attr("x", 10)
  .attr("y", 10)
  .attr("width", 80)
  .attr("height", 80)
  .style("fill", "green");
// end (d3js) * * * * * * * * * * * * * * * * * * * * * * * *

console.log( window.d3.select("body").html() );

which outputs:

<svg width="100" height="100"><rect id="rect1" x="10" y="10" width="80" height="80" style="fill: green;"></rect></svg>

Related Query

More Query from same tag