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
Post a Comment