Handle WebPack CSS imports when testing with Mocha

2019-02-08 12:10发布

问题:

When testing .js files that have Webpack CSS imports like import './style.css', Mocha throws a syntax error (because it tries to import and parse the CSS file as JS). There is a solution for this that has already been posted on Stack Overflow, but it only addresses if you aren't already using a compiler with Mocha. I'm using Babel 5. I've tried the following, but it seems that Mocha doesn't support passing multiple compilers:

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

Is there a way to have multiple Mocha compilers, or a better way to tell Mocha not to try to parse Webpack CSS imports?


EDIT:

I like the proposed solution by @Giles B below; it was exactly what I needed. However, since I am still on Babel 5 I needed a few tweaks as shown below:

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 script

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

This is working for me using babel and babel-core, both version 5.8.23.

回答1:

I came across the same problem and just got it working, so in my mocha.opts file I added the following require calls:

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

In babelhook.js I have one require statement to load 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")();

Then from the link you provided I setup css-null-compiler.js as follows:

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

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

Hope that helps.



回答2:

Based on @Giles' answer above, this is what I used to get working on 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;

This enables you to have your tests inside your src folder alongside your components.