Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery with jsdom@5?

I am migrating from node.js to io.js and my old node.js code does not work with jsdom@5.

var jsdom=require('jsdom');
var $=require('jquery')(jsdom.jsdom().createWindow);

Here is the error:

/tmp/iojs/node_modules/jquery/dist/jquery.js:28
                                if ( !w.document ) {
                                       ^
TypeError: Cannot read property 'document' of undefined
    at module.exports (/tmp/iojs/node_modules/jquery/dist/jquery.js:28:12)
    at Object.<anonymous> (/tmp/iojs/test.js:2:24)
    at Module._compile (module.js:431:26)
    at Object.Module._extensions..js (module.js:449:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:472:10)
    at startup (node.js:124:18)
    at node.js:959:3

I am using latest io.js v2.0.1, [email protected] and [email protected].

What is the right way to use jQuery with jsdom@5?

like image 835
untitled Avatar asked May 13 '15 19:05

untitled


People also ask

Can I use jQuery in Nodejs?

js: We can use jQuery in Node. js using the jquery module. Note: Use the 'jquery' module not the 'jQuery' module as the latter is deprecated.

What is Jsdom for?

JSDOM is a library which parses and interacts with assembled HTML just like a browser. The benefit is that it isn't actually a browser. Instead, it implements web standards like browsers do. You can feed it some HTML, and it will parse that HTML.


2 Answers

Looking at the documentation https://github.com/tmpvar/jsdom. This should work for [email protected]

var jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { window } = new JSDOM('<html></html>');
var $ = require('jquery')(window);
like image 57
addousas Avatar answered Sep 19 '22 15:09

addousas


The following is more in-line with what you are trying to do. Check out the repo

 // using Version 5.4.1
 var jsdom = require('jsdom').jsdom;
 var document = jsdom('<html></html>', {});
 var window = document.defaultView;
 var $ = require('jquery')(window);

The concrete problem with your original code is that it uses the createWindow API, which was removed in jsdom 1.0.0-pre.1. (Note that the document.parentWindow suggested in that change log entry was then itself removed in 4.0.0.)

like image 21
undefined Avatar answered Sep 18 '22 15:09

undefined