如何在 Webpack 和 Babel 中使用 TheIntern

How to use TheIntern with Webpack and Babel

我尝试使用 theintern 进行我的 Units/Fonctionals 测试,但我将 webpack 用于 bundling/loading 模块,将 webpack-dev-server 用于本地开发,将 babel 用于转译 JS。

当我尝试加载一个组件时,我的组件中导入的文件出现错误。

// 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

然后在我的测试文件中:

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

但是,当我加载我的测试套件时,出现如下错误:

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

我使用 jsdom 启用 window,它适用于 c.js 但不适用于其他模块。

那么,如何配置 theintern 以在没有 SystemJS 和 Typescript 的情况下处理来自 webpack 的模块?

问题是 c.js 假定 window 在全局范围内。虽然 createwindow.js 创建一个 jsdom window,但它不会将其添加到全局范围。

一种解决方案是将jsdom的window添加到全局范围:

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

然而,正如 jsdom 作者指出的那样,这 isn't a good practice。相反,您的测试 class 应该使用您的 createWindow 插件来获取 window:

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