Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test es6 module that imports jquery with jsdom

I am struggling to get mocha, jsdom, es6 modules with babel to play nice with jquery.

Here's a module

// lib/dom.js
import $ from 'jquery';

const node = (tag)=> $(`<${tag} />`)

export {
  node
}

Here's a test

// test/dom.js
import assert from 'assert';
import { node } from '../src/lib/dom';

describe('node(tag)', ()=> {
  it('should return a Node', ()=> {
    let img = node('img');
    assert(img.nodeName === 'IMG');
  });
});

Here's the jsdom setup

// test/_setup.js
var jsdom = require('jsdom');

global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = document.parentWindow;

The script to run

mocha --compilers js:babel-register --recursive

What do I need to change to allow jsdom to load jquery so that dom.js can load the jquery module without getting the error:

Error: jQuery requires a window with a document

Here's the full source https://github.com/markbrown4/test-simple

like image 514
markbrown4 Avatar asked Jan 20 '16 03:01

markbrown4


1 Answers

Got it, test/_setup.js needed the following:

global.document = require('jsdom').jsdom('<html></html>');
global.window = document.defaultView;
global.$ = require('jquery')(window);

document.parentWindow is deprecated from jsdom.

like image 117
markbrown4 Avatar answered Sep 22 '22 06:09

markbrown4