我正在尝试使用Karma来测试一个使用d3.js绘制图表的简单脚本。 该脚本使用browserify导入d3 。
var d3 = require('d3'); // Some code...我已将Karma配置为使用browserify和PhantomJS对此文件运行测试,但无论配置如何,它始终会因此错误而失败:
PhantomJS 1.9.8 (Mac OS X 0.0.0) ERROR TypeError: 'null' is not an object (evaluating 'node.getAttribute')我尝试使用browserify-shim但没有任何区别。 这是我的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']任何帮助解决这个问题将不胜感激。 只是为了澄清一下,实际的代码工作得很好,只有通过Karma它才会破坏。
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.
最满意答案
问题是我试图测试的脚本是在HTML body的末尾加载并使用d3自动触发一个函数。 当通过Karma运行时,它会在DOM加载之前注入脚本,这会导致d3失败,因为它期望DOM元素存在。
修复是从脚本中删除函数调用并将其添加到我的HTML body的末尾:
<body> <!-- HTML code --> <script> myFunction(); </script> </body>由于browserify使事情变得尴尬,您还必须将该函数附加到窗口对象,以便从脚本外部调用它:
window.myFunction = function() { // code }这现在可以在浏览器中使用并使用Karma。
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.
更多推荐
发布评论