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 .
You can create your own mock in jest to prevent processing of css files. // __mocks__/styleMock. js module. exports = {};
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.
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.
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 = {};
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",
//...
},
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With