Skip to content Skip to sidebar Skip to footer

Handle Webpack Css Imports When Testing With Mocha And Babel

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 so

Solution 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 optionsrequire("babel-register")();

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

// Prevent Mocha from compiling classfunctionnoop() {
  returnnull;
}

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

Hope that helps.

Solution 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 filesfunctionnoop() {
  returnnull;
}

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

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

Post a Comment for "Handle Webpack Css Imports When Testing With Mocha And Babel"