Skip to content

Instantly share code, notes, and snippets.

@robballou
Created October 29, 2014 23:04
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robballou/9ee108758dc5e0e2d028 to your computer and use it in GitHub Desktop.
Save robballou/9ee108758dc5e0e2d028 to your computer and use it in GitHub Desktop.
Testing jQuery code in Mocha
// The hacky bit of this approach is that this module uses
// jQuery, but it is not referenced here. This is because I
// am populating it in the test via global namespace.
//
// In the browser this still works because I am adding jQuery
// via a Browserify transform (browserify-global-shim).
function someModule() {
}
modules.export = someModule;
someModule.doStuff = function() {
jQuery('body').append('<div class="some-module"></div>');
}
var should = require('should'),
assert = require('assert'),
jsdom = require('jsdom');
var someModule = require('./someModule');
describe('someModule', function() {
// create some jsdom magic to allow jQuery to work
var doc = jsdom.jsdom(html),
window = doc.parentWindow,
$ = global.jQuery = require('jquery')(window);
it('does stuff', function() {
someModule.doStuff();
$('div.some-module').length.should.equal(1);
});
});
@carylwyatt
Copy link

@swashata Thanks for posting-- this helped me out of a jam! 👍

@gdibble
Copy link

gdibble commented Dec 4, 2018

@wlcdesigns That code snippet is gold; concise, functional and helpful - thanks!

@omnoms
Copy link

omnoms commented Dec 14, 2018

I'm having issues with this now...

 AssertionError: expected [TypeError: $ is not a function] to be undefined

From this testfile.

const expect = require('chai').expect;
describe("myjquerytest", function () {
    it('should not throw an exception parsing the JS file', function () {
        try {
            const { JSDOM } = require('jsdom');
            const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
            const { window } = jsdom;
            const { document } = window;
            global.window = window;
            global.document = document;
            global.$ = global.jQuery = require('jquery')(window);
            var test = $(document);
        } catch (err) {
            expect(err).to.be.undefined;
        }
    });
});

The problem, as I can see it, is that jQuery and $ are not defined as functions but as objects, and can't be used as a function with $(document). So I'm guessing I should assign $ to something else... maybe the result of jQuery.fn.init? or something?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment