Jest遇到意外标记

axzmvihb  于 2022-12-08  发布在  Jest
关注(0)|答案(9)|浏览(194)

Not sure why it's complaining on this line:
const wrapper = shallow(<BitcoinWidget {...props} />);

/Users/leongaban/projects/match/bitcoin/src/components/bitcoinWidget.test.js: Unexpected token (17:26)

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:
  15 |
  16 | describe('when rendering', () => {
 >17 |   const wrapper = shallow(<BitcoinWidget {...props} />);
  18 |                           ^
  19 |   it('should render a component matching the snapshot', () => {
  20 |     const tree = toJson(wrapper);

Entire test:

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);
  });
});

The component

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;

And my 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"
  }
}
7cjasjjr

7cjasjjr1#

将其添加到package.json jest配置中。

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

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

yqhsw0fo

yqhsw0fo2#

对于任何使用create-react-app的人来说,在使用create-react-app时,只有某些jest配置可以在package.json中更改。
我在使用Jest拾取内部库时遇到问题,无论我从该库导入什么内容,Jest都会显示“意外标记”错误。
要解决这个问题,你可以把你的测试脚本更改为下面的:"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",

ttisahbt

ttisahbt3#

对于任何人谁挣扎与这个问题,没有以上的答案为他/她工作。
经过长时间的寻找,我找到了这个解决办法
编辑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]

rqmkfv5c

rqmkfv5c4#

I also encountered the same error while setting up Jest in my React app created using Webpack. I had to add @babel/preset-env and it was fixed. I have also written a blog article about the same.
npm i -D @babel/preset-env
And then add this in "presets" in .babelrc file. E.g.

{ 
  "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

cetgtptt

cetgtptt5#

我将jest更新添加到我的package.json

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

如果不需要,请随意移除|<second-package-name>
您也可以将其作为脚本的一部分来执行@paulosullivan22
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<package-name>)/)'"

sbdsn5lh

sbdsn5lh6#

在我的例子中,问题是我在模拟模块中导入了原始模块:

import urlExist from "url-exist";

async function stubbedUrlExist(): Promise<boolean> {
  // do something
}

export default stubbedUrlExist;

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

pbpqsu0x

pbpqsu0x7#

下面的工作对我来说。创建babel.config.js文件。

module.exports = {
presets: [
    [ '@babel/preset-env', { targets: { esmodules: true } } ],
    [ '@babel/preset-react', { runtime: 'automatic' } ],
],

};

wgeznvg7

wgeznvg78#

以下内容适合我

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

oyjwcjzk9#

could not get it working with transforms, I ended up mocking the dependency:
Create a file: /react-markdown.js

import React from 'react';

function ReactMarkdown({ children }){
  return <>{children}</>;
}

export default ReactMarkdown;

On jest.config.js file add:

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

credits to juanmartinez on https://github.com/remarkjs/react-markdown/issues/635

相关问题