笑话遇到了意外的令牌-导入'promise-polyfill / src / polyfill'中断测试

时间:2018-12-27 15:42:39

标签: reactjs jestjs babel-jest

当我将其添加到代码中时,我的Jest测试就会中断:

import 'promise-polyfill/src/polyfill';

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

我的package.json是:

{
  "name": "fas-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "ajv": "^6.5.3",
    "babel": "^6.23.0",
    "babel-polyfill": "^6.26.0",
    "connected-react-router": "^4.4.1",
    "formik": "^1.1.1",
    "hello.js": "^1.0.0",
    "hellojs": "^2.0.0-4",
    "history": "^4.7.2",
    "immutability-helper": "^2.8.0",
    "loadjs": "^3.5.4",
    "moment": "^2.22.2",
    "promise-polyfill": "8.1.0",
    "react": "^16.4.2",
    "react-bs-notifier": "^5.0.0",
    "react-datepicker": "^1.6.0",
    "react-dom": "^16.4.2",
    "react-facebook-login": "^4.0.1",
    "react-ga": "^2.5.6",
    "react-google-oauth": "^1.0.0",
    "react-redux": "^5.0.7",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-scripts": "^2.1.1",
    "react-tooltip": "^3.9.0",
    "recharts": "^1.3.0",
    "redux": "^4.0.0",
    "redux-thunk": "^2.3.0",
    "whatwg-fetch": "^3.0.0",
    "yup": "^0.26.6"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "jest": "^23.6.0"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

我尝试设置此处记录的配置内容:

https://jestjs.io/docs/en/configuration.html#modulenamemapper-object-string-string

我不知道要添加到哪个文件或如何设置它。 polyfill所做的全部是提供IE支持,因此Jest不需要(或可以模拟它),我只是想不出如何使Jest在测试中模拟它。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

就像您创建一个React-Redux应用程序并仅与酶一起使用来测试它一样。

如果您要创建一个单页应用程序,则最好的做法是创建一个索引页面来设置环境并呈现您的App组件。

如果您在此处设置环境(例如promise-polyfill),则可以保证该环境将在项目的其余部分中出现。

您还将使用以下内容呈现该应用程序:

ReactDOM.Render(App/>, document.getElementById('root'))

但是,不应定期测试过程的索引部分。对于一个,您必须在jsdom中添加一个ID为'root'的元素。

相反,您应该测试不应导入索引页面的App组件本身。