I have jQuery plugin that I'm testing. I found this question: How to run Jasmine tests on Node.js from command line? but when I run:
node_modules/jasmine-node/bin/jasmine-node --verbose --junitreport --noColor spec
I got errors that $ is not defined. How can I include jQuery? (Right now I only test utilities that don't interact with the dom).
In order to test a Node. js application, the jasmine framework needs to be installed first. This is done by using the Node package manager. The test code needs to be written in a separate file, and the word 'spec' should be appended to the file name.
jasmine-jquery provides two extensions for the Jasmine JavaScript Testing Framework: a set of custom matchers for jQuery framework. an API for handling HTML, CSS, and JSON fixtures in your specs.
You will first need to create a DOM that jQuery can do its thing on. You should set this up as a global variable, as you are probably accessing jQuery (or $) on the window element.
First, add jquery and jsdom to your package.json file, eg:
"dependencies": {
"jquery": "*"
},
"devDependencies": {
"jsdom": "*"
}
Run npm install
to install the new dependencies you just added.
Then, at the top of your spec file, do something like this:
var jsdom = require("jsdom").jsdom;
global.window = jsdom().parentWindow;
global.jQuery = global.$ = require("jquery")(window);
This creates a window element using jsdom, and lets jquery know what to act on. You should now be able to access both jQuery
and $
in your specs.
I've had some difficulty getting this to work too. What I've found works (by going to the jsdom github page: https://github.com/tmpvar/jsdom) is to do the following.
Install the following two packages (as suggested by Farid):
npm install jquery --save
npm install jsdom --save-dev
Then at the top of your spec (test) file type the following:
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM(`<!DOCTYPE html>`);
global.jQuery = global.$ = require("jquery")(window);
global.window = window;
global.document = window.window;
Now you have set $
, window
and document
globally. This is my first time using javascript, so if I have done something wrong, please let me know!
P.S. There is a neat way to run your tests using npm (I learnt it from here: https://www.keithcirkel.co.uk/how-to-use-npm-as-a-build-tool/).
Inside your package.json
file add a "scripts" section, e.g.
{
"dependencies": {
"jquery": "^3.2.1"
},
"devDependencies": {
"jasmine-node": "^1.14.5",
"jsdom": "^10.1.0"
},
"scripts": {
"test": "jasmine-node --verbose --color spec/*"
}
}
Now you can run your tests by simply typing:
npm run test
or just npm test
for short.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With