Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "$ is not defined" error when unit testing Jquery with Typescript using Mocha?

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.

like image 951
Aditi Avatar asked Jul 26 '16 13:07

Aditi


2 Answers

I found this question in 2020 and Louis got me pointing in the right direction. However, I found jsdom-global an easier alternative way of getting document working in Mocha. I installed jsdom-global following the instructions at jsdom-global

I used these lines to get jQuery and $ working as expected:

require('jsdom-global')();
global.window = window;
global.$ = require('jquery');
global.jQuery = $;

Then this test passed with flying colours:

const assert = require("chai").assert;
function test(){
    return "test";
}
describe('Setting up global constants...', function () {
    describe('Libraries...', function () {
        it('jQuery and $ are present', () => {
            assert(jQuery !== undefined);
            assert($ !== undefined);
            assert($ === jQuery);
            assert($.isFunction(test));
        });
    });
});
like image 180
DavidHyogo Avatar answered Oct 07 '22 08:10

DavidHyogo


You need to include jsdom and jQuery in Node first:

npm install jsdom --save-dev
npm install jquery --save-dev

and then add this lines into your .js file where you are using jQuery

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM(`...`);
var jQuery = require('jquery')(window);

var example = (function($) {
 .....your jQuery code....
})(jQuery);

module.exports = example;
like image 24
Jorge Luis Monroy Avatar answered Oct 07 '22 08:10

Jorge Luis Monroy