WebPack CSS import processing when testing with Mocha and Babel

When testing .js files that have Webpack CSS import './style.css' , such as 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 which has already been published on Stack Overflow , but it is only addressed if you are not already using the compiler with Mocha. I am using Babel 5. I have tried the following, but it seems that Mocha does not 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 the Webpack CSS import?




EDIT:

I like the proposed @Giles B solution below; that was exactly what i needed. However, since I'm still on Babylon 5, I needed a few settings, 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 works for me using babel and babel-core , as of version 5.8.23 .

+14
javascript css webpack babeljs mocha
Nov 23 '15 at 21:33
source share
2 answers

I ran into 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 instructions for loading 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 install css-null-compiler.js as follows:

 // Prevent Mocha from compiling class function noop() { return null; } require.extensions['.css'] = noop; require.extensions['.scss'] = noop; 

Hope this helps.

+15
Dec 03 '15 at 19:02
source share

Based on @Giles answer above, this is what I used to work 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 allows you to run tests inside your src folder along with your components.

+5
May 12 '16 at 10:33
source share



All Articles