I've set up mocha to run tests in the terminal. It works for basic test like expect(1).to.equal(1). The problem I run into is that my script is wrapped in the jQuery like so jQuery( function( $ ) { // my code here }); and I get an error when running the tests.
evalmachine.<anonymous>:15
jQuery( function ( $ ) {
^
ReferenceError: jQuery is not defined
at evalmachine.<anonymous>:15:1
at Object.exports.runInThisContext (vm.js:54:17)
at Suite.<anonymous> (/Users/grahamlutz/Documents/BBC/poolproof/test/test.js:21:8)
at context.describe.context.context (/usr/local/lib/node_modules/mocha/lib/interfaces/bdd.js:47:10)
at Object.<anonymous> (/Users/grahamlutz/Documents/BBC/poolproof/test/test.js:8:1)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at /usr/local/lib/node_modules/mocha/lib/mocha.js:220:27
at Array.forEach (native)
at Mocha.loadFiles (/usr/local/lib/node_modules/mocha/lib/mocha.js:217:14)
at Mocha.run (/usr/local/lib/node_modules/mocha/lib/mocha.js:469:10)
at Object.<anonymous> (/usr/local/lib/node_modules/mocha/bin/_mocha:404:18)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:141:18)
at node.js:933:3
my test.js looks like this:
var assert = require('assert');
var chai = require('chai');
var expect = chai.expect;
var fs = require('fs');
var vm = require('vm');
var jsdom = require('mocha-jsdom');
describe('mocha tests', function () {
jsdom();
before(function () {
$ = require('jquery');
});
var path = __dirname + '/../wp-content/themes/bb-theme-child/myscript.js';
var code = fs.readFileSync(path);
vm.runInThisContext(code);
describe('getSession', function() {
it('should return the empty string because it fails', function () {
applyCoupon();
});
});
});
My question is either why is jQuery undefined or what incorrect assumptions am I making? Do I need to change the way I think about testing javascript within a wordpress set up?
The following two lines worked for me. For convenience I just put these at the top of my mocha test file. I used 'jsdom-global' package instead of 'mocha-jsdom' per the recommendation on the mocha-jsdom github readme. https://github.com/rstacruz/jsdom-global
this.jsdom = require('jsdom-global')()
global.$ = global.jQuery = require('jquery');
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