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.
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 usingd3
. When ran throughKarma
it injects the script before theDOM
has loaded, which causesd3
to fail as it was expecting aDOM
element to exist.The fix was to remove the function call from the script and add it at the end of my
HTML 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:This now works both in the browser and using Karma.