I am writing Mocha unit tests for Typescript code containing Jquery. I'm using jsdom for getting the document object. When I compile my TS code to JS and run the tests, it throws an error [ReferenceError: $ is not defined].
My Typescript code is here
export function hello(element) : void {
$(element).toggleClass('abc');
};
My unit test code is as follows:
import {hello} from '../src/dummy';
var expect = require('chai').expect;
var jsdom = require('jsdom');
var document = jsdom.jsdom();
var window = document.defaultView;
var $ = require('jquery')(window);
describe('TEST NAME', () => {
it('should run', (done) => {
hello($('div'));
done();
});
});
When I run Mocha test it shows
<failure message="$ is not defined"><![CDATA[ReferenceError: $ is not defined ...
]]></failure>
Also tried using global.$ = require("jquery"); but does not work.
You need to include jsdom and jQuery in Node first:
and then add this lines into your .js file where you are using jQuery
jQuery has to be available globally because your script gets it from the global space. If I modify your code so that
var $ = require('jquery')(window);
is replaced by:then it works. Note the two calls: 1st to require
jquery
, then to build it by passingwindow
. You could alternatively do:If
window
is available globally, then there is no need to perform the double call as in the first snippet: jQuery just uses the globally availablewindow
.You probably also want to define
global.jQuery
since some scripts count on its presence.Here is a full example of a test file that runs:
The
typings
files are obtained the usual way usingtsd
. The file./global.d.ts
fixes the issue you may get with setting new values onglobal
. It contains:dummy.js
was also modified like this:If you can't or don't want to alter the global namespace type definition, you can still include jQuery, as following:
The full initialization of jQuery then becomes:
As said, you should import jQuery properly:
import $ = require('jquery');