Jest快照@import CSS失败

时间:2018-01-23 14:22:14

标签: javascript css reactjs testing jest

我无法将@import用于我当前的jest设置

npm run test

> test5@0.0.1 test /var/www/test5
> jest

 FAIL  src/components/Menu/index.spec.js
  ● Test suite failed to run

    /var/www/test5/src/components/Menu/style.css:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){@import "../shared/vars.css";
                                                                                             ^

    SyntaxError: Invalid or unexpected token

       7 | 
       8 | //Styles
    >  9 | import style from './style.css';
      10 | 
      11 | class Menu extends React.Component {
      12 |  constructor (props){

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:318:17)
      at Object.<anonymous> (src/components/Menu/index.js:9:14)
      at Object.<anonymous> (src/components/Menu/index.spec.js:3:14)

的style.css

@import "../shared/vars.css";

.menu {
  background: #322e31;
  color: $wtext;
  width: 80vw;
  max-width: 400px;
  position: fixed;
  right: -80vw;
  top: 0;
  height: 100vh;
  z-index: 3;

  h2,h3 {
    font-size: 16px;
    display: inline-block;
  }
}

的package.json

  "jest": {
    "setupTestFrameworkScriptFile": "./node_modules/jest-enzyme/lib/index.js",
    "moduleFileExtensions": [
      "js"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "testPathIgnorePatterns": [
      "<rootDir>/node_modules/",
      "<rootDir>/app/"
    ],
    "moduleNameMapper": {
      "moduleNameMapper": {
        "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
        "\\.(css)$": "identity-obj-proxy"
      }
    },
    "transform": {
      "^.+\\.js$": "babel-jest"
    }
  }

1 个答案:

答案 0 :(得分:0)

对我有用的配置是:

"moduleNameMapper": {
  "^[./a-zA-Z0-9$-]+\\.png$": "<rootDir>/src/public/__mocks__/ImageAndStyleDummy.js",
  "^[./a-zA-Z0-9$-]+\\.css$": "<rootDir>/src/public/__mocks__/ImageAndStyleDummy.js"
}   

您需要将路径<rootDir>/src/public/__mocks__/ImageAndStyleDummy.js更改为您自己的模拟。您甚至可以根据实现使用fileMock.js,只需将css扩展名添加到已存在的正则表达式中,然后删除专用于此扩展名的行。或者按照相同的模式创建一个专门用于css的新文件。