There are several descriptions of how to run html-embedded scripts with JSDOM, yet I would like to run a function declared in the normal node.js context with a global object from jsdom, like:
import { JSDOM } from 'jsdom';
function addHello() {
document.body.innerHTML = '<p>hello</p>';
}
const html = '<html><head></head><body></body></html>';
const jsdom = new JSDOM(html, { runScripts: 'outside-only' });
jsdom.window.addHello = addHello;
jsdom.window.eval('addHello()');
According to the JSDOM documentation I thought the runScripts option does the trick, but when running the above code with node I get
document.body.innerHTML = '<p>hello</p>';
^
ReferenceError: document is not defined
at addHello (file:///.../jsdomTryout.js:4:3)
Note that addHello is only an example. In the real case, it is a method from some larger library and I would prefer to import it in the above script rather than instructing JSDOM to load that library via <script> tags.
Is there a way to get what I want with JSDOM? My suspicion is that this is not possible, because of the way the global object of a function is determined, but maybe there is some "magic" available.
EDIT: Meanwhile I learned that what I am really missing is <script type="module"> support from jsdom to let me have something like
<script type="module">import 'some-library';</script>
in the html I pass to jsdom and go from there.