Created
October 29, 2014 23:04
-
-
Save robballou/9ee108758dc5e0e2d028 to your computer and use it in GitHub Desktop.
Testing jQuery code in Mocha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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>'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
@wlcdesigns That code snippet is gold; concise, functional and helpful - thanks!
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
@swashata Thanks for posting-- this helped me out of a jam! 👍