使用 Mocha 和 Babel 测试时处理 WebPack CSS 导入

Handle WebPack CSS imports when testing with Mocha and Babel

当测试 .js 具有 Webpack CSS 导入的文件时,如 import './style.css',Mocha 抛出一个语法错误(因为它尝试导入和解析 CSS 文件作为JS)。这个 有一个解决方案,但它仅适用于您尚未使用带有 Mocha 的编译器的情况。我正在使用 Babel 5。我尝试了以下方法,但似乎 Mocha 不支持传递多个编译器:

// npm test script

mocha ./src/**/*Test.js --compilers css:./scripts/mocha-webpack-compiler.js js:babel/register

// scripts/mocha-webpack-compiler.js

function noop() {
  return null;
}

require.extensions['.css'] = noop;

有没有办法拥有多个 Mocha 编译器,或者有更好的方法告诉 Mocha 不要尝试解析 Webpack CSS 导入?


编辑:

我喜欢下面@Giles B 提出的解决方案;这正是我所需要的。但是,由于我仍在使用 Babel 5,因此我需要进行一些调整,如下所示:

mocha.opts

--require scripts/support/babelhook
--require scripts/support/mocha-webpack-compiler

scripts/babelhook.js

require('babel/register');

scripts/mocha-webpack-compiler.js

function noop() {
    return null;
}
require.extensions['.css'] = noop;

摩卡脚本

mocha ./src/**/*Test.js

我使用 babelbabel-core 这两个版本 5.8.23

我遇到了同样的问题并让它正常工作,所以在我的 mocha.opts 文件中我添加了以下 require 调用:

--require test/babelhook
--require test/css-null-compiler

babelhook.js 中,我有一个加载 babel 的 require 语句:

// This file is required in mocha.opts
// The only purpose of this file is to ensure
// the babel transpiler is activated prior to any
// test code, and using the same babel options

require("babel-register")();

然后从 link 你 我设置 css-null-compiler.js 如下:

// Prevent Mocha from compiling class
function noop() {
  return null;
}

require.extensions['.css'] = noop;
require.extensions['.scss'] = noop;

希望对您有所帮助。

根据上面@Giles 的回答,这就是我在 Babel 6 上的工作

package.json

"scripts": {
  "test": "mocha --compilers js:babel-core/register 
          --require ./tools/testHelper.js 'src/**/*-spec.@(js|jsx)'",

tools/testHelper.js

// Prevent mocha from interpreting CSS @import files
function noop() {
  return null;
}

require.extensions['.css'] = noop;

这使您能够在 src 文件夹中与组件一起进行测试。