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

tre*_*ler 15 javascript css mocha.js webpack babeljs

当测试.js具有Webpack CSS导入的文件时import './style.css',Mocha会抛出语法错误(因为它尝试将CS​​S文件导入并解析为JS).有一个解决方案已经发布在Stack Overflow上,但只有在你还没有使用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;
Run Code Online (Sandbox Code Playgroud)

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


编辑:

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

mocha.opts

--require scripts/support/babelhook
--require scripts/support/mocha-webpack-compiler
Run Code Online (Sandbox Code Playgroud)

脚本/ babelhook.js

require('babel/register');
Run Code Online (Sandbox Code Playgroud)

脚本/摩卡的WebPack-compiler.js

function noop() {
    return null;
}
require.extensions['.css'] = noop;
Run Code Online (Sandbox Code Playgroud)

摩卡脚本

mocha ./src/**/*Test.js
Run Code Online (Sandbox Code Playgroud)

这对我使用babelbabel-core两个版本都有用5.8.23.

Gil*_*ler 16

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

--require test/babelhook
--require test/css-null-compiler
Run Code Online (Sandbox Code Playgroud)

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

// 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")();
Run Code Online (Sandbox Code Playgroud)

然后从您提供的链接我设置css-null-compiler.js如下:

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

require.extensions['.css'] = noop;
require.extensions['.scss'] = noop;
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.


mum*_*bot 5

基于@Giles上面的回答,这就是我以前在Babel 6上工作的原因

的package.json

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

工具/ testHelper.js

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

require.extensions['.css'] = noop;
Run Code Online (Sandbox Code Playgroud)

这使您可以在组件旁边的src文件夹中进行测试.