Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

javascript - jest unexpected token when importing css

I got error of SyntaxError: Unexpected token .

in my code

import 'react-dates/lib/css/_datepicker.css'
import 'semantic-ui-css/semantic.min.css'

those isn't in my spec.js but my implementation code, any clue why? I have no problem running my app but jest throw error when I try to run test.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that Jest is hitting these CSS imports and trying to parse them as if they were JavaScript.

The "Unexpected token ." message probably comes because the first line of the file it is choking on is a CSS class declaration, i.e. .datepicker: { ... }.

Anyway, as pointed out in this answer, the way to get around this is to create a file containing a module which exports an empty object. I called mine styleMock.js.

module.exports = {};

Then, you need to create a jest.config.js file in your project root and add:

module.exports = {
  moduleNameMapper: {
    '\.(css|less)$': '<rootDir>/test/jest/__mocks__/styleMock.js',
  }
};

The moduleNameMapper setting tells Jest how to interpret files with different extensions. In this case we simply need to point it at the empty file we just created. Obviously adjust the path to your file accordingly.

And note that you can expand the regex above for whichever file endings you need. Mine looks like:

moduleNameMapper: {
  '\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
    '<rootDir>/test/jest/__mocks__/fileMock.js',
  '\.(css|less)$': '<rootDir>/test/jest/__mocks__/styleMock.js',
},

where fileMock.js is identical to styleMock.js

Alternatively, you could use a module such as jest-transform-stub, which does the same thing for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...