Search code examples
webpackintern

How to use TheIntern with Webpack and Babel


I try to use theintern to make my Units/Fonctionals Tests, but I use webpack for bundling/loading modules, webpack-dev-server for local developement and babel for transpilling JS.

When I try to load a component I have error from a file who are imported by an import in my component.

// a.js
const getWindowLocation = window.location
export default getWindowLocation

// b.js
import getWindowLocation from "a.js"
const anotherVar = getWindowLocation
// make some work with anotherVar
export default anotherVar

// c.js
import anotherVar from "b.js"
// module i try to test
const something = somevalue
export default something

Then in my test file :

// test.c.js
import something from "c.js"

But, when i load my test suite i have an error like :

ReferenceError: window is not defined
at getWindowLocation  <a.js>
at Object.<anonymous>  <b.js>

I use jsdom to enable windowand it's work for c.js but not for other module.

So, how to configure theintern to handle modules from webpack without SystemJS and Typescript ?


Solution

  • The issue is that c.js assumes window is in the global scope. While createwindow.js creates a jsdom window, it doesn't add it to the global scope.

    One solution is to add jsdom's window to the global scope:

    // createwindow.js
    const jsdom = require('jsdom')
    const { JSDOM } = jsdom
    const { window } = new JSDOM()
    global.window = window;
    

    However, as the jsdom authors point out, this isn't a good practice. Instead, your test class should use your createWindow plugin to get window:

    // c.js
    const window = intern.getPlugin('createWindow');
    const getWindowLocation = window.location
    export default getWindowLocation