Testing javascript using d3 with Karma

519 views Asked by At

I'm trying to use Karma to test a simple script that uses d3.js to draw a chart. The script uses browserify to import d3.

var d3 = require('d3');
// Some code...

I have configured Karma to use browserify and PhantomJS to run tests against this file, however no matter the config it always fails with this error:

PhantomJS 1.9.8 (Mac OS X 0.0.0) ERROR
TypeError: 'null' is not an object (evaluating 'node.getAttribute')

I tried using browserify-shim but it made no difference. Here is an excerpt of my karma.conf.js:

frameworks: ['browserify', 'mocha'],

files: [
  'src/static/js/*.js',
  'test/js/*.js'
],

preprocessors: {
  'src/static/js/*.js': ['browserify'],
  'test/js/*.js': ['browserify']
},

browserify: {
  debug: true,
  transform: ['debowerify', 'browserify-shim']
},

browsers: ['PhantomJS']

Any help solving this problem would be greatly appreciated. Just to clarify, the actual code works fine, it's only through Karma that it breaks.

1

There are 1 answers

0
Ben On BEST ANSWER

The problem was that the script I was trying to test was being loaded at the end of the HTML body and automatically triggering a function using d3. When ran through Karma it injects the script before the DOM has loaded, which causes d3 to fail as it was expecting a DOM element to exist.

The fix was to remove the function call from the script and add it at the end of my HTML body:

<body>
    <!-- HTML code -->
    <script>
        myFunction();
    </script>
</body>

Since browserify makes things awkward, you must also attach the function to the window object in order to call it from outside the script:

window.myFunction = function() {
    // code
}

This now works both in the browser and using Karma.