3

I'm using Jest in my project and got stuck on one test which contains SCSS variable.

$grey-light: #C7C7C7;

I get this Jest error:

Jest encountered an unexpected token

and it points on the previous mentioned line of code.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Yaniv Or
  • 57
  • 1
  • 6
  • 1
    Are you compiling your scss code? Make sure you're using the compiled css and not the scss file – Itay Gal Sep 20 '18 at 08:26
  • I'm not compiling the scss code, just import it whenever needed. BTW, it's a React project. – Yaniv Or Sep 20 '18 at 11:05
  • scss is not a valid css, the browser don't know how to read it. You need to compile it first, this will generate the css file, then you can import the generated css file. – Itay Gal Sep 20 '18 at 11:07
  • 1
    Actually, my scss is getting compiled. It's a React project with webpack, babel etc. The browser gets the compiled css. The only issue is with Jest. – Yaniv Or Sep 20 '18 at 11:53
  • 1
    The library I'm using for compilation is: sass-loader – Yaniv Or Sep 20 '18 at 11:55
  • Are you using the variable in your JS files? and how/where? [Rodrigo's answer](https://stackoverflow.com/a/53907088/1218980) works well with irrelevant classnames when using CSS modules (obfuscated classes), but when using variables, we do need the values and the identity proxy is not enough. – Emile Bergeron Oct 16 '19 at 00:26

2 Answers2

8

I ran into this as well and it was solved by using the identity-obj-proxy package:

https://github.com/keyz/identity-obj-proxy

Just follow the instructions in the Jest docs:

https://jestjs.io/docs/en/webpack#mocking-css-modules

And should run the tests with no issues regarding the .scss files import statements. All you have to do is include the jest configuration in your package.json file:

{
  "name": "...",
  "version": "0.0.0",
  "description": "...",
  "main": "index.js",
  "scripts": {
    "start": "webpack --config webpack.config.js",
    "test": "jest"
  },
  "jest": {
    "moduleNameMapper": {
      "\\.(css|scss|less)$": "identity-obj-proxy"
    }
  },
  "keywords": [],
  "author": "Homer Jay",
  "license": "MIT",
  "devDependencies": {},
  "dependencies": {}
}

And the .scss imports will work as expected and any variable or mixin won't throw an error.

Rodrigo
  • 1,638
  • 1
  • 15
  • 27
-3

Sass helps you write more organized and maintainable code, but it's not a vaild css code, thus, browsers don't know how to read it.

scss files needs to be compiled into css, and you need to import and use the css files. For example, the parameter you define has the #C7C7C7 value. The compiler will replace that parameter with that value so the final css will only contain hard-coded values

Itay Gal
  • 10,706
  • 6
  • 36
  • 75