1

I'm getting jQuery requires a window with a document error and it seems that I need an answer like: Error: jQuery requires a window with a document

What I'm looking for is the correct syntax for this using import rather than require because I'm not require-ing anything else in my Node app. I'm trying to get this to work in a React component. I tried:

import jsdom from 'jsdom';
import $ from 'jquery';

jsdom.jsdom().createWindow();

and:

import jsdom from 'jsdom';
const $ = require('jquery')(jsdom.jsdom().createWindow());

But that's not getting me there. How do I resolve this?

jmargolisvt
  • 5,722
  • 4
  • 29
  • 46
  • 1. you are using React. surprised to find you need jquery. in most cases you dont, see http://youmightnotneedjquery.com/ 2. require-ing vs import-ing depends on your bundler and what it can resolve and how it can resolve it. take a look at https://www.npmjs.com/package/jquery for how to include jquery for your bundler. 3. it seems like your issue is more cosmetic that it is a real issue, if require works, I'd go with that. – Ahmed Musallam Jan 25 '18 at 20:40
  • As @AhmedMusallam said, `require` might be better for you. Have you tried: `const $ = require('jquery')(jsdom.jsdom().createWindow());` ? – Jordan Kasper Jan 25 '18 at 21:04

1 Answers1

0

NOTE: This only works for older versions of jsdom.

I do this for the tests for using jQuery Mockjax in a Node context. Essentially, I use the jsdom env() method to generate the window object with a blank HTML document:

const jsdom = require('jsdom');
let $;

jsdom.env('<html></html>', function (error, window) {
    if (error) {
        // handle this somehow
    } else {
        $ = require('jquery')(window);
        // now you have it...
    }
});
Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55