18
votes

Testing Components

I am trying to run some very simple tests on react components with Jest. I am running into problems because of this line at the top of my component file

import {} from './style.less';

The import here doesn't need to be tested and would ideally be ignored from the test.

Result of [npm test]

When the test is run via npm test I get the response

FAIL tests/app_test.js ● Runtime Error SyntaxError: Unexpected token { in file 'client/components/app/style.less'.

Make sure your preprocessor is set up correctly and ensure your 'preprocessorIgnorePatterns' configuration is correct: http://facebook.github.io/jest/docs/api.html#preprocessorignorepatterns-array-string If you are currently setting up Jest or modifying your preprocessor, try jest --no-cache. Preprocessor: node_modules/jest-css-modules. Jest tried to the execute the following preprocessed code: //some .less code

But if I comment out the less import line my test runs correctly.

Question

How can I get jest to skip over this line of code or ignore this import?

4
Check this solution stackoverflow.com/a/36137733/2765745 Worked for me. - Pavel Hasala

4 Answers

12
votes

The only way I could get jest to ignore less files for me, other than manually mocking the .less file at the top of the test e.g.

jest.mock("../../src/styles.less", () => jest.fn());

Was to add the following to the package.json:

"jest": {
 "moduleNameMapper": {
  ".*\\.less$": "<rootDir>/pathToDummyFile/dummy.js"
  }
 },

Whenever your code tries to import a less file it will instead redirect the import to fetch an empty dummy file, which will avoid the unexpected token error you experienced.

12
votes

If you still have this issue, try to add the following config to your jest.config.json file:

"transform": { "^.+\\.(css|less)$": "./styleMock.js" }

Here, in your styleMock.js you're creating a transformer which will transform your .less files like this:

module.exports = { process() { return '' } }

6
votes

A little late to the party but maybe this will help someone today. Use jest-transform-stub.

In your Jest config, add jest-transform-stub to transform non JavaScript assets you want to stub:

{
  "jest": {
    // ..
    "transform": {
      "^.+\\.js$": "babel-jest",
      ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
    }
  }
}

FAQ

My module isn't being transformed

Jest doesn't apply transforms to node_modules by default. You can solve this by using moduleNameMapper:

{
  "jest": {
    // ..
    "moduleNameMapper": {
      "^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
    }
  }
}
1
votes

I've solved same problem with ignore-styles(https://github.com/bkonkle/ignore-styles). I've used this lib with mocha but I think it should be ok with jest.