Ian Dickinson Ian Dickinson - 2 months ago 14
Javascript Question

ES2015 import of jQuery not working in test case

I'm trying to use ES2015 modules on a new project, and get that working with unit testing with Mocha and Chai via gulp. I'm importing jQuery into the source module (so that it can call

getJSON()
), but while the main
$
function seems to be present, the functions attached to it - like
getJSON
or
attr
- are not.

Here's a minimal test case:

// minimal-test-case.js
import $ from "jquery";

export function minimalTestCase1() {
return $;
}

export function minimalTestCase2() {
return $.getJSON;
}


And here's the corresponding test for it:

// minimal-test-case-test.js
import {expect} from "chai";
import {describe, it} from "mocha";
import {minimalTestCase1, minimalTestCase2} from "../../../app/es/services/minimal-test-case.js";

describe("a minimal test case", () => {
it( "should be able see jquery", () => {
expect(minimalTestCase1()).to.be.a.function;
} );

it( "should be able see jquery functions", () => {
expect(minimalTestCase2()).to.not.be.undefined;
} );
});


Test case 1 succeeds, but test case 2 fails.

The corresponding gulp task is:

function testUnitTask() {
return gulp
.src(["test/unit/**/*.js"])
.pipe(gulpMocha({
compilers:babelCompiler
}));
}
gulp.task("test:unit", testUnitTask);


The
import
pattern seems to be one that I've seen used elsewhere. Why can't I see
$.getJSON
?

Answer

More than likely you're getting the dummy function jQuery exports when it detects that it is in a commonjs environment and when no global document is available. I advise adding jsdom to your test setup and adding a minimal setup file like this

const jsdom = require('jsdom').jsdom;
global.document = jsdom('<body></body>');
global.window = document.defaultView;
global.navigator = window.navigator;
global.XMLHttpRequest = window.XMLHttpRequest;
Comments