Jest: Jest doesn't works with JSX which imports CSS

Created on 7 Mar 2017  ·  24Comments  ·  Source: facebook/jest

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
If app.jsx have import './app.css'; it's impossible to run test, I got this error:

yarn run:test v0.21.3
$ NODE_ENV=client jest -u
 FAIL  src/__tests__/app.test.js
  ● Test suite failed to run

    /home/svipben/Documents/react-boilerplate/src/client/app/app.css:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){body {
                                                                                                  ^
    SyntaxError: Unexpected token {

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at Object.<anonymous> (src/client/app/app.jsx:7:1)
      at Object.<anonymous> (src/__tests__/app.test.js:2:12)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.693s
Ran all test suites.
error Command failed with exit code 1.

What is the expected behavior?
To run tests without error...

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

OS: Linux Ubuntu 16.04
Jest: Latest
Yarn: Latest
Node: Latest
babel-jest: Latest

.babelrc:

        "client": {
            "presets": [
                "latest", // All you need to compile what's in ES2015+
                "flow", // Flow support
                "react", // Strip flow types and transform JSX
                "stage-2" // Experimental syntax extensions
            ],
            "sourceMaps": true // Compile with Source Maps
        },

jest: NODE_ENV=client jest -u

P.S. Everything runs well if I comment/remove import './app.css';

Most helpful comment

I solved this by using the moduleNameMapper key in the jest configurations in the package.json file

{
   "jest":{
        "moduleNameMapper":{
             "\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
             "\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
        }
   }
}

After this you will need to create the two files as described below

  • __mocks__/styleMock.js
module.exports = {};
  • __mocks__/fileMock.js
module.exports = 'test-file-stub';

If you are using CSS Modules then it's better to mock a proxy to enable className lookups.
hence your configurations will change to:

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

But you will need to install identity-obj-proxy package as a dev dependancy i.e.

yarn add identity-obj-proxy -D

For more information. You can refer to the jest docs

All 24 comments

@maximderbin Thanks!

@maximderbin Thank you! It resolves my issue by adding moduleNameMapper

@svipben @maximderbin @simonxl where do I have to add this moduleNameMapper?
I see in the doc that we shall add it in the packag.json but which one?
tnx

@sarahmarciano moduleNameMapper is a part of your configuration. By default, you can set the config in package.json (the one which features jest in dependencies) under "jest" key, like this:

{
  "dependencies": {...}
  "jest": {
    "moduleNameMapper": {...}
  }
}

I solved this by using the moduleNameMapper key in the jest configurations in the package.json file

{
   "jest":{
        "moduleNameMapper":{
             "\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
             "\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
        }
   }
}

After this you will need to create the two files as described below

  • __mocks__/styleMock.js
module.exports = {};
  • __mocks__/fileMock.js
module.exports = 'test-file-stub';

If you are using CSS Modules then it's better to mock a proxy to enable className lookups.
hence your configurations will change to:

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

But you will need to install identity-obj-proxy package as a dev dependancy i.e.

yarn add identity-obj-proxy -D

For more information. You can refer to the jest docs

Note that the approaches recommended here will not work if your CSS modules export values which your JSX files depend on. Most guides assume you're only using CSS modules to export class names. I wish there was a guide for properly mocking CSS modules.

@matthew-dean what do you mean "properly mocking CSS modules"? Can you describe your use case a bit more? I have great experience using identity-obj-proxy

:export {
  sizeMobile: $size-mobile / 1px;
  sizePhablet: $size-phablet / 1px;
  sizeSmallTablet: $size-small-tablet / 1px;
  sizeTablet: $size-tablet / 1px;
  sizeDesktop: $size-desktop / 1px;
  sizeLargeDesktop: $size-large-desktop / 1px;
}
import styles from './variables.scss'

const tileSize = parseFloat(styles.sizeTablet) / 3
//...
render() {
  return <Tile style={{width: tileSize}} />
}

This is a contrived example, just demonstrating that you can share constants (values) between CSS modules and JS, and that conditional rendering or dynamic props can be assigned based on values.

But with identity-obj-proxy, these values can't be cast to integers, let alone the actual values that are present. So if you have JSX code that relies on constants defined in your CSS modules, then you can't test this without properly mocking the CSS module (having an object returned that has the values as testable integers). identity-obj-proxy only assumes that your CSS modules contain an object with nothing more than scoped CSS classnames; it does not support the other aspect of CSS modules which is the ability to export values / constants that in turn get used in JS operations.

@SimenB

Incidentally, I WAS able to mock the CSS module successfully like this:

const styles = require('styles/variables.scss')

jest.mock('styles/variables.scss', () => {
  return {
    sizePhablet: 500,
    sizeSmallTablet: 768,
    sizeTablet: 1024,
    sizeDesktop: 1440,
    sizeLargeDesktop: 1920
  }
})

Hopefully that's useful for someone else who is using all the features of CSS modules and, like me, was tearing their hair out at all the default "just use identity-obj-proxy" advice.

I solved this problem by using 'jest-transform-css'.
After installing, added the below in the jest config.

"transform": {
      "^.+\\.js$": "babel-jest",
      ".+\\.(css|styl|less|sass|scss)$": "jest-transform-css"
    }

Now css files will get transpiled just like js files did.

@matthew-dean where did you write the mock the CSS module and how do you reference it to jest?

I'm using an external package and it imports its own files to a single file by using the following:
@import "progress-tracker/progress-tracker-variables.scss";

Whenever I run the Jest for to start testing
image
the error above shows up. I already have specified css mockup inside the package.json
image

Im looking forward to get some help about that issue. Any tricks, suggestions?

Edit: I have tried both babel-jest and identity-obj-proxy packages and none of those worked. The problem still persists.

Edit 2: Also I have tried the config below according to solutions that I have come across with on the web.
image

I'm using Babel 7, babel-jest ^24.5.0, Jest ^24.1.0.

After following the above advice, I'm still getting this error when I try to import a function or object into a Jest test file (e.g. Post.test.js) when the target file (e.g. Post.js) imports a CSS file - e.g. ./postStyles.css.

Jest encountered an unexpected token

SyntaxError: Unexpected token .

Details:

    /Users/ben/Desktop/Work/code/bengrunfeld/src/front-end/components/Post/postStyles.css:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.post h1, .post h2, .post h3 {

      3 |
      4 | import { PostText } from './styles'
    > 5 | import './postStyles.css'

As per the article linked above, this is in my package.json:

"jest": {
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules", "bower_components", "shared"],

    "moduleNameMapper": {
      "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
      "\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js",

      "^react(.*)$": "<rootDir>/vendor/react-master$1",
      "^config$": "<rootDir>/configs/app-config.js"
    }
  },

and in the root directory, I have __mocks__/styleMock.js which has the following code:

module.exports = {};

Lastly, my jest.config.js:

module.exports = {
  setupFiles: ['<rootDir>/src/test/setup.js']
}

Which in turn configures Enzyme:

import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

Enzyme.configure({ adapter: new Adapter() })

import Error
I am struggling to solve almost same issue where my scss file contain @import statements. Test fails telling SyntaxError: Invalid or unexpected token. Can somebody help me please?

I followed solutions given above but none of them seems to be working for me

I was able to resolve this by adding @babel/polyfill as a dev dependency

same here @fthomas82

I solved this by using the moduleNameMapper key in the jest configurations in the package.json file

{
   "jest":{
        "moduleNameMapper":{
             "\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
             "\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
        }
   }
}

After this you will need to create the two files as described below

  • __mocks__/styleMock.js
module.exports = {};
  • __mocks__/fileMock.js
module.exports = 'test-file-stub';

If you are using CSS Modules then it's better to mock a proxy to enable className lookups.
hence your configurations will change to:

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

But you will need to install identity-obj-proxy package as a dev dependancy i.e.

yarn add identity-obj-proxy -D

For more information. You can refer to the jest docs

It worked for me. Thanks!!!

I solved this problem by using 'jest-transform-css'.
After installing, added the below in the jest config.

"transform": {
      "^.+\\.js$": "babel-jest",
      ".+\\.(css|styl|less|sass|scss)$": "jest-transform-css"
    }

Now css files will get transpiled just like js files did.

Thanks, bro @krajasekhar
It works for me 👍

I added suggested config to packages.json, without success, then I realized I had a jest.config.js in my project root directory, Jest uses that config file over packages.json.

For reference here is my jest.config.js file:

module.exports = {
  setupFilesAfterEnv: ['<rootDir>/.setup-tests.js'],
  testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.+\\.(css|styl|less|sass|scss)$': 'jest-transform-css',
  },
};

I have to import a raw css in my code

import "./cloud.css?raw"

I also modified jest config
"jest":{ "moduleNameMapper": { "\\.(css|less|scss|sass|css?raw)$": "identity-obj-proxy" },

still, I am getting test error on the import line. Any idea how to mock raw import?

Solution of @import Unexpected token=:)

Install package:
npm i --save-dev identity-obj-proxy

Add in jest.config.js

module.exports = {
  "moduleNameMapper": {
    "\\.(css|less|scss)$": "identity-obj-proxy"
  }
}

If somebody arrives here:
This module is the most updated I have seen: https://www.npmjs.com/package/jest-css-modules-transform

transform: { '^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/babel-jest', ".+\\.(css|styl|less|sass|scss)$": "jest-css-modules-transform" }, transformIgnorePatterns: [ '/node_modules/', '^.+\\.module\\.(css|sass|scss)$', ], moduleNameMapper: { '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy' },

I added suggested config to packages.json, without success, then I realized I had a jest.config.js in my project root directory, Jest uses that config file over packages.json.

For reference here is my jest.config.js file:

module.exports = {
  setupFilesAfterEnv: ['<rootDir>/.setup-tests.js'],
  testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.+\\.(css|styl|less|sass|scss)$': 'jest-transform-css',
  },
};

Thanks to everybody who presented a solution and specially to you @Shadoow! It was a kind of logic thing but I was missing that ... config file will be used over settings in package.json

In short, for new comers, what worked to me was an union of multiple solutions presented by our community dream team:

1) create a jest.config.json file

touch jest.config.json open jest.config.json

2) Install jest-transform-css:

yarn add jest-transform-css -D

3) This is how your jest config file should look like:

module.exports = {
  preset: 'ts-jest/presets/js-with-babel',
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': './jest.mock.js',
  },
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/assets/'],
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '\\.(css|less|scss|sass)$': 'jest-transform-css',
  },
};

4) Update your package.json (first, transfer all your JEST configurations, if you have some there, to the new jest config file), then the magic goes here:

"test": "jest --config ./jest.config.js"

Tks Everyone !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mmcgahan picture mmcgahan  ·  3Comments

hramos picture hramos  ·  3Comments

StephanBijzitter picture StephanBijzitter  ·  3Comments

samzhang111 picture samzhang111  ·  3Comments

ianp picture ianp  ·  3Comments