3

I can't seem to get jsdom to execute external scripts and I can't seem to find any concrete examples. I don't get any error when I call my testing function, but nothing happens.

This is my code:

    var window = jsdom.jsdom(body).createWindow();

    jsdom.jQueryify(window, './lib/jquery.js', function () {
      console.log(window.$("#a1").text());
      window.testing();
      console.log(window.$("#a2").text());
    });

This is the html its loading:

<html>
    <head>
            <script type="text/javascript" src="stuff.js"></script>
    </head>
    <body>
    Hi there

    <div id="a1">
    </div>

    <div id="a2">
    </div>

 </body>
</html>

My testing function:

function testing() {
    var a2 = document.getElementById("a2");
    a2.innerHTML = 'Second div';
    console.log("executed");
 }

1 Answer 1

3

Check out the jsdom docs

Try this before the rest of your code:

require('jsdom').defaultDocumentFeatures = {
  FetchExternalResources   : ['script'], 
  ProcessExternalResources : ['script'],
  MutationEvents           : '2.0',
  QuerySelector            : false
}

var window = jsdom.jsdom(body).createWindow();

jsdom.jQueryify(window, './lib/jquery.js', function () {
  console.log(window.$("#a1").text());
  window.testing();
  console.log(window.$("#a2").text());
});

/fyi #node.js IRC welcomes you: http://bit.ly/nodeIRC

3
  • This answer is wrong after the latest updates. MutationEvents needs to be "2.0" instead of false.
    – Bjorn
    Jan 20, 2012 at 7:32
  • what is body here ?
    – R.Anandan
    Jan 22, 2019 at 6:27
  • body is the html for your page - definitely check out the latest docs for jsdom, probably a lot has changed
    – DTrejo
    Apr 17, 2019 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.