The issue is pretty simple: $
is not defined in the context in which your code executes. The fix is to add to your callback the parameters window
and $
. They are initialized by jQueryify
as you'd expect. The following outputs to the console everything you wanted:
var jsdom = require("jsdom");
var document = jsdom.jsdom();
var window = document.parentWindow;
jsdom.jQueryify(window, "jquery-1.10.2.js", function (window, $) {
try {
$(window).scroll(function(){
console.log("Scroll Happened.");
});
console.log("Triggering Scroll event..."); // 1
$(window).trigger('scroll');
console.log("Scroll event triggered."); // 2
}
catch (ex) {
console.log(ex);
}
});
I've added the try ... catch
for illustration purposes. If you remove window, $
from the parameters, you can see that the try ... catch
catches a ReferenceError
because $
is not defined.
The lesson here is that jsdom effectively creates a new JavaScript virtual machine in which it executes the scripts loaded by the window. So symbols that are defined in this virtual machine are not necessarily defined outside of it. And symbols of the same name that are defined inside the jsdom virtual machine and outside of it do not generally point to the same object. (For instance, console
outside the virtual machine created by jsdom and console
inside of it are not the same object.)