美文网首页
Test case import antd

Test case import antd

作者: JellyL | 来源:发表于2019-01-16 23:34 被阅读30次

    Error

     Jest encountered an unexpected token
    
        This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
    
        By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
    
        Here's what you can do:
         • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
         • If you need a custom transformation specify a "transform" option in your config.
         • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
    
        You'll find more details and examples of these config options in the docs:
        https://jestjs.io/docs/en/configuration.html
    
        Details:
    
        /Users/yjlu@thoughtworks.com/Code/Git/Porsche/cool-frontend/node_modules/antd/es/notification/style/css.js:1
        ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import '../../style/index.css';
                                                                                                 ^^^^^^
    

    Test environment

    "antd": "^3.11.2",
    "@babel/core": "7.1.0",
    "babel-jest": "^23.6.0",
    "jest": "^23.6.0",

    // .babelrc
    {
      "presets": ["@babel/react","@babel/env"],
      "plugins": [
        "transform-class-properties",
        ["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }]
      ]
    }
    

    Root cause

    babel-jest does not transpile import/export in node_modules when Babel 7 is used #6229

    Solution

    1. rename .babelrc to babel.config.js which will export .babelrc object.
    2. Adding transformIgnorePatterns to my Jest config in package.json:
    "transformIgnorePatterns": [
          "/node_modules/antd/es/notification/style/index.js"
    ],
    
    1. create a mock style js file <rootDir>/__mocks__/styleMock.js
    // styleMock.js
    module.exports = {};
    

    And use it in 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)$": "<rootDir>/__mocks__/styleMock.js"
        }
    

    After I did these 3 steps, I found that it takes a long time to run my test cases. And after I add node_modules in moduleDirectories in jest config, it runs smoothly.

    // jest.config.json
    "moduleDirectories": ["....", "node_modules"]
    

    相关文章

      网友评论

          本文标题:Test case import antd

          本文链接:https://www.haomeiwen.com/subject/kizvdqtx.html