Search code examples
javascriptunit-testingbrowserifyjsdomnode.js-tape

How to use jsdom in a file which is bundled with Browserify?


I am trying to create a unit test for a function. In the test, I would like to emulate the global document object (e.g. document.getElementById()) using the jsdom package. I have installed jsdom in my project, and to my test file (test.pageContent.js) added a single line:

const jsdom = require('jsdom')

But from the command line, when I Browserify this file then execute it, it fails with this output:

>> node_modules/.bin/browserify test.pageContent.js -t [ babelify ] --outfile test-bundle.js && node test-bundle.js

Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db
C:\Users\snarl\development\project\test-bundle.js:59075
module.exports = typeof self == 'object' ? self.FormData : window.FormData;

ReferenceError: window is not defined

Why is that occurring and how can I resolve it?

I am Browserifying in this manner because the function-under-test is in an ES6 module, which itself calls other ES6 modules. If I don't Browserify and Babelify like this, errors occur. Maybe this is what needs to be investigated on my end?


Of Note

  • From the command line, if I execute the test file with the Browserify command, but without any Babelify transform, the same error occurs.

  • From the command line, if I execute the test file without the Browserify command at all, there is no error at all.

  • I am using Tape as my unit test harness.


Solution

  • After discussing with the jsdom devs, the answer to my question is that things are working as intended with jsdom in this case. The two supported jsdom use cases are:

    • using jsdom as a CommonJS module in Node or
    • using jsdom in a Browserify bundle in web browsers

    In my case, I'm trying to use jsdom in a Browserify bundle in Node. I will try to use it in a browser and see how I go. Initial tests look promising.