CSS module @import fails the Jest test suit

2019-07-09 02:00发布

问题:

I am using Jest and Enzyme to test my application. I am getting error:

 FAIL  app/containers/Navbar/NavbarContainer.test.js
  ● Test suite failed to run

    app/components/Navbar/styles.css: Unexpected token (1:0)
      > 1 | @import "../../styles/base/_variables";
          | ^
        2 |
        3 | .navbar{
        4 |   width: $navbar-width;

This is my Jest configuration in package.json:

"jest": {
    "verbose": true,
    "globals": {
      "env": {
        "isProd": false,
        "isDev": true,
        "command": "start"
      }
    },
    "moduleNameMapper": {
      "\\.(css)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "js",
      "jsx",
      "json",
      "css"
    ],
    "modulePaths": [
      "/app"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "verbose": true,
    "setupFiles": [
      "./setupJest.js"
    ],
    "setupTestFrameworkScriptFile": "<rootDir>/setupTests.js"
  }

I was following the guides while setting up the application, and I found that identity-obj-proxy will help to mock css-modules functionality, but that's not working in my case. Please let me know what am I missing here.

P.S. this is about not ES6 modules import. The suit failed because there is a @import in css.

回答1:

So, I've found the solution to this problem. I was importing CSS without the extension in my components and Jest was confusing that import with JS file. Solution is instead of importing css like:

import * as styles from './styles'

you should import it like:

import * as styles from './styles.css'


回答2:

One quick gotcha that I found with this. If you have a jest.config.js file, then you need to set your moduleNameWrapper inside of that config file.



回答3:

UPDATE who use create-react-app from feb 2018. You cannot override the moduleNameMapper in package.json but in jest.config.js it works, unfortunately i havent found any docs about why it does the trick. So my jest.config.js look like this:

module.exports = {
...,
  "moduleNameMapper": {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
    "\\.(scss|sass|css)$": "identity-obj-proxy"
  }
}

and it skips scss files and @import quite well.

I added to devDependencies identity-obj-proxy

Backing my answer i followed jest webpack