javascript - How can I fix "ReferenceError: $ is not defined" when using jQuery with mocha-jsdom? -


i'm setting es6 unit tests in project , having trouble making them work libraries. thought i'd use jquery test try , make work. without libraries, tests work.

note jquery imported main.js file available throughout project.

my js file looks this:

class test {   constructor(options) {     this.init();   }    init() {     $('.test-div').addclass('test');   }    sayhello() {     return 'hello world!';   } }  export default test; 

and test looks this:

import jsdom 'mocha-jsdom'; import chai 'chai'; import test './test';  chai.should();  describe('frequency', () => {    var $;   jsdom();    before(() => {     $ = require('jquery');   })    it('should output hello world', () => {       const test = new test();       test.sayhello().should.equal('hello world!');   });  }); 

if remove init() function, test works. however, before function doesn't seem import jquery test. error receive in console follows:

referenceerror: $ not defined   @ frequency.init 

i copied code , got work modifying before hook to:

before(() => {   $ = require('jquery');   global.$ = $; }); 

if read mocha-jsdom's documentation you'll see puts in global space symbols window , document. when load jquery, finds window , adds window.$. in browser, also makes $ visible in global space because window is global space. in node, however, global space global, , have put $ in yourself.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -