Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jest trying to parse .css

I have a problem with jest in which no matters what I do it keeps trying to parse the css files as javascript.

The files build properly with webpack.

I have the following configuration for jest

"jest": {
    "rootDir": "./src",
    "moduleNameMapper": {
      "^.*[.](css|CSS)$": "../jest/styleMock.js"
    }
  },

I also tried a script preprocessor to strip the css from the imports:

 "jest": {
    "rootDir": "./src",
    "scriptPreprocessor": "../node_modules/jest-css-modules"
  },

It keeps throwing the error.

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.button {
                                                                                             ^
    SyntaxError: Unexpected token .
like image 261
Onza Avatar asked Sep 22 '16 13:09

Onza


People also ask

How do I make jest ignore CSS?

You can create your own mock in jest to prevent processing of css files. // __mocks__/styleMock. js module. exports = {};

Does jest use webpack config?

Luckily for most projects, Jest should be more than flexible enough to handle your webpack config. For more complex webpack configurations, you may also want to investigate projects such as: babel-plugin-webpack-loaders.

What is CSS modules?

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. CSS Modules let you write styles in CSS files but consume them as JavaScript objects for additional processing and safety.


2 Answers

The best solution is to use a moduleNameMapper line in your Jest config, as described in the Jest docs.

A minimal "ignore css" jest config, in package.json, might like this

  "jest": {
    "moduleNameMapper": { "\\.(css|less)$": "<rootDir>/assets/css/__mocks__/styleMock.js" }
  },

Then styleMock.js is just this

module.exports = {};
like image 97
Jonathan Stray Avatar answered Oct 01 '22 11:10

Jonathan Stray


I don't know if it's the best way, but considering I've been stuck here for a while, I am posting the solution.

In order to fix it, I had to do two steps:

1) The @Jonathan Stray solution so add a moduleNameMapper pointing to a js mock (see his response for more details)

2) Then I had to install the jest-css-modules-transform plugin, and add it in the jest configuration inside the package.json like below:

"jest": {
    //...
    "transform": {
        ".+\\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform",
        //...
    },
    //...
}
like image 31
quirimmo Avatar answered Oct 01 '22 11:10

quirimmo