【问题标题】:Jest encountered an unexpected tokenJest 遇到了意外的令牌
【发布时间】:2022-03-31 21:53:57
【问题描述】:

不知道为什么在这条线上抱怨:

const wrapper = shallow(<BitcoinWidget {...props} />);

整个测试:

import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';

// Local components
import BitcoinWidget from './bitcoinWidget';

const props = {
  logo: 'foobar',
  coin: {
    price: 0
  },
  refresh: jest.fn()
}

describe('when rendering', () => {
  const wrapper = shallow(<BitcoinWidget {...props} />);

  it('should render a component matching the snapshot', () => {
    const tree = toJson(wrapper);
    expect(tree).toMatchSnapshot();
    expect(wrapper).toHaveLength(1);
  });
});

组件

import React from 'react';

const BitcoinWidget = ({ logo, coin : { price }, refresh }) => {
  return (
    <div className="bitcoin-wrapper shadow">
      <header>
        <img src={logo} alt="Bitcoin Logo"/>
      </header>
      <div className="price">
        Coinbase
        ${price}
      </div>
      <button className="btn striped-shadow white" onClick={refresh}>
        <span>Refresh</span>
      </button>
    </div>
  );
}

export default BitcoinWidget;

还有我的 package.json

{
  "name": "bitcoin",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "react-redux": "^5.0.7",
    "react-scripts": "1.1.5",
    "redux": "^4.0.0",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "eject": "react-scripts eject",
    "test": "yarn run test-jest:update --verbose --maxWorkers=2",
    "test-jest:update": "jest src --updateSnapshot",
    "test-jest": "jest src"
  },
  "now": {
    "name": "bitcoin",
    "engines": {
      "node": "8.11.3"
    },
    "alias": "leongaban.com"
  },
  "jest": {
    "verbose": true,
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/client/assetsTransformer.js"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ]
  },
  "devDependencies": {
    "enzyme": "^3.4.4",
    "enzyme-to-json": "^3.3.4",
    "jest": "^23.5.0"
  }
}

【问题讨论】:

    标签: javascript reactjs jestjs


    【解决方案1】:

    将此添加到您的 package.json jest 配置中。

    "transform": {
          "\\.js$": "<rootDir>/node_modules/babel-jest"
        },
    

    如果问题仍然存在,请告诉我。

    【讨论】:

    • 我也失踪了babel-plugin-transform-es2015-destructuringbabel-plugin-transform-object-rest-spreadenzyme-adapter-react-15eslint-config-airbnb
    • 太好了。第一次配置 jest 时会发生这种情况。我也经历过同样的情况。很高兴您的问题已解决。
    • 我也面临同样的问题,@LeonGaban 你提到那里缺少图书馆......你能告诉它是什么吗?
    • @AnupamMaurya 我在评论中列出了它们。
    • 帮助很大。太好了。
    【解决方案2】:

    对于使用 create-react-app 的任何人,在使用 create-react-app 时,只能在 package.json 中更改某些 jest 配置。

    我在使用 Jest 获取内部库时遇到问题,无论我从该库导入什么,Jest 都会显示“意外令牌”错误。

    要解决此问题,您可以将测试脚本更改为以下内容: "test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(&lt;your-package-goes-here&gt;)/)'",

    【讨论】:

    • 这对我有用,在使用外部库的类似情况下。
    【解决方案3】:

    我在使用 Webpack 创建的 React 应用程序中设置 Jest 时也遇到了同样的错误。我必须添加@babel/preset-env 并且它已修复。我也写了一篇关于相同的博客文章。

    npm i -D @babel/preset-env

    然后将其添加到.babelrc 文件的“预设”中。例如

    { 
      "presets": ["@babel/react", "@babel/env"]
    }
    

    https://medium.com/@shubhgupta147/how-i-solved-issues-while-setting-up-jest-and-enzyme-in-a-react-app-created-using-webpack-7e321647f080?sk=f3af93732228d60ccb24b47ef48d7062

    【讨论】:

      【解决方案4】:

      对于那些在这个问题上苦苦挣扎并且以上答案都不适合他/她的人。

      搜索了很久,终于找到了这个解决方案

      编辑您的 jest.config.js 以添加 transformIgnorePatterns

      //jest.config.js
      
      module.exports = {
          preset: 'ts-jest',
          testEnvironment: 'jsdom',
          testMatch: ["**/__tests__/**/*.ts?(x)", "**/?(*.)+(test).ts?(x)"],
          transform: {
              "^.+\\.(js|ts)$": "ts-jest",
          },
          transformIgnorePatterns: [
              "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.js$",
              "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.ts$",
              "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.tsx$",
          ],
      }
      

      把你想忽略的包放在[]里面,用|

      隔开

      在我的情况下[@autofiy/autofiyable|@autofiy/property]

      【讨论】:

      • 老实说,我不知道这是导致这个问题的原因
      【解决方案5】:

      我将开玩笑的更新添加到我的package.json

      "jest": {
        "transformIgnorePatterns": [
          "node_modules/(?!(<package-name>|<second-package-name>)/)"
        ]
      },
      

      如果不需要,请随时删除|&lt;second-package-name&gt;

      您也可以将其作为@paulosullivan22 提到的脚本的一部分进行

      "test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(&lt;package-name&gt;)/)'"

      【讨论】:

        【解决方案6】:

        就我而言,问题在于我在模拟模块中导入了原始模块:

        import urlExist from "url-exist";
        
        async function stubbedUrlExist(): Promise<boolean> {
          // do something
        }
        
        export default stubbedUrlExist;
        

        解决方案是不要在 url-exist 模拟中导入 url-exist。这可能导致循环导入。 Jest 可能在处理模块加载的通用 trycatch 块中捕获了此错误。

        【讨论】:

          【解决方案7】:

          以下对我有用

          module.exports = {
            presets: [
              ["@babel/preset-env", { targets: { node: "current" } }],
              "@babel/preset-typescript", "@babel/react"
            ]
          };
          

          【讨论】:

            【解决方案8】:

            无法让它与转换一起使用,我最终模拟了依赖项:

            创建一个文件:/react-markdown.js

            import React from 'react';
            
            function ReactMarkdown({ children }){
              return <>{children}</>;
            }
            
            export default ReactMarkdown;
            

            在 jest.config.js 文件中添加:

            module.exports = {
              moduleNameMapper: {
                'react-markdown': '<path>/mocks/react-markdown.js',
              },
            };
            

            感谢https://github.com/remarkjs/react-markdown/issues/635上的juanmartinez

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2019-12-13
              • 1970-01-01
              • 2021-12-07
              • 1970-01-01
              • 1970-01-01
              • 2019-03-22
              • 2019-08-24
              相关资源
              最近更新 更多