0

According to the JSDom README, you can pass an array of Javascript Strings to execute, but it seems like this feature isn't working for me.

This is my node app:

var fs = require('fs');
var jsdom = require('jsdom-no-contextify');

var scripts = ['manipulate-dom.js'];
var src = scripts.map(function(filename) {
    return fs.readFileSync(filename, 'utf8');
});

console.log(src[0]);

jsdom.env({
    html: '<div>Hi</div>',
    src: src,
    done: function(errors, window) {
        console.log(window.document.querySelector('div').textContent);
        window.doStuff();
        console.log(window.document.querySelector('a').textContent);
    }
});

and this is my other file:

console.log('Running JS');

function doStuff() {
    var a = document.createElement('a');
    a.textContent = 'TEXT!';
    window.document.body.appendChild(a);
}

window.doStuff = doStuff;

The output is as follows:

console.log('Running JS');

function doStuff() {
    var a = document.createElement('a');
    a.textContent = 'TEXT!';
    window.document.appendChild(a);
}

window.doStuff = doStuff;
Hi

...
        window.doStuff();
               ^
TypeError: Object #<Window> has no method 'doStuff'

It doesn't even print "Running JS". What am I doing wrong?

7
  • this is the output that's displaying in the console? or the browser? if that's what's displaying in the browser, then you're not referencing your "other file" correctly Commented Mar 6, 2015 at 22:25
  • @DaRod I'm running Node command-line, and the output quoted is what I saw. The source code in the output is proof that I've loaded the second file; the code just isn't getting executed. Commented Mar 6, 2015 at 22:27
  • are you using this with node.js or io.js? Commented Mar 6, 2015 at 23:02
  • @DaRod Node version 10; JSDom version 3. Commented Mar 6, 2015 at 23:06
  • i found this post that may help: github.com/tmpvar/jsdom/issues/640#issuecomment-22216965 It basically describes that sometimes the scripts haven't finished loading before "done" gets hit. if this was the case, then window.doStuff= doStuff wouldn't have been assigned before you call window.doStuff(), hence the error. Try this, instead of assigning calling window.doStuff(), try just calling doStuff() and see if that function is available. that assignment is redundant anyway. Commented Mar 6, 2015 at 23:16

1 Answer 1

2

try observing what's in the "errors" object. from the documentation: If window creation succeeds and no s cause errors, then errors will be null, and window will be usable.

Your issue will probably be revealed in there. =)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.