Jest语法错误:意外的符号<

16
我想使用TypeScript在React应用程序中使用Jest Enzyme测试组件。我遵循了Jest网站上的说明,但出现了以下错误:

SyntaxError: Unexpected token <

我可以测试一些函数,没有任何问题,但是当我使用一个组件时,就会出现错误。这是文件package.json中的Jest配置:
"jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testMatch": ["**/__tests__/*.(ts|tsx)"],
    "snapshotSerializers": ["enzyme-to-json/serializer"],
    "setupFilesAfterEnv": ["<rootDir>/src/setupEnzyme.ts"],
    "unmockedModulePathPatterns": ["node_modules/react/", "node_modules/enzyme/"]
  }

酶配置

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

export default class TesComponent extends Component {
    render(){
        return (
            <div>test</div>
        )
    }
}

import { shallow } from 'enzyme'
import TestCompoenent from '../TestComponent'

test('component testing', () => {
    const component = shallow(<TestCompoenent />)
    expect(component.contains(<div>test</div>)).toBeTruthy()
})

这是错误:

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:

    /home/user/Documents/local-platform/frontend/src/pages/__tests__/settigs.test.tsx:9
        var component = enzyme_1.shallow(<TestComponent_1.default />);
                                         ^

    SyntaxError: Unexpected token <

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)

我希望测试能够通过,因为测试组件包含<div>test</div>

请同时发布您的 TestComponent 组件。 - ravibagul91
我已经编辑了帖子。 - Davit Yeritsyan
1
Try jest --clearCache - ravibagul91
得到了相同的错误:( - Davit Yeritsyan
有没有NextJs的解决方案? - Ronald Araújo
有一行代码写着“TesComponent”,少了个“t”(export default class TesComponent),另一行代码写着“TestCompoenent”,多了一个“e”(import TestCompoenent from '../TestComponent'),最后还有一行是“TestComponent”。这到底是哪一个? - Peter Mortensen
3个回答

28

尝试更改tsconfig.json

"jsx": "preserve" -> "jsx": "react"


1
该选项指定输出应如何生成(即JSX语法转换为类型检查)。详情请参见https://www.typescriptlang.org/docs/handbook/jsx.html#basic-usage。 - Pramod Mali
4
终于解决了!!以防万一,将其更改为“react”修复了我的主要问题。然而,它会抛出一些其他错误。通过将其替换为react-jsx,由Dan Barclay提到的方法解决了这个问题。(https://dev59.com/VVIG5IYBdhLWcg3whggn#65539274) - Hans Araya
2
这在Next.js中无法工作。- jsx被设置为preserve(Next.js实现了自己优化的jsx转换)。 - programandoconro

3

@babel/plugin-transform-react-jsx作为插件添加到babel.config.js中,解决了我的问题。

module.exports = {
  presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
  plugins: ['@babel/plugin-transform-react-jsx'],
};

我希望这对任何人都有所帮助。在找到这个方法之前,我花了几个小时尝试不同的方法。


如果你能分享一下你找到那个的地方,那就更有用了 :-) - undefined

2

看起来你的配置无法正确处理 TypeScript 文件(.tsx)。

这是我的一部分工作配置:

"jest": {
    "transform": {
       "^.+\\.tsx?$": "ts-jest",
    },
    "moduleFileExtensions": [
       "ts",
       "tsx",
       "js",
       "json"
    ],
    "setupTestFrameworkScriptFile": "<rootDir>/src/setupSpecs.ts"
}

我使用了 setupTestFrameworkScriptFile 而不是 setupFilesAfterEnv


当我按回车键继续时,我收到消息,提示“选项“setupTestFrameworkScriptFile”已被配置“setupFilesAfterEnv”替换,该配置支持多个路径”,然后我又收到了相同的错误。 - Davit Yeritsyan
加上 "moduleFileExtension" 怎么样? - Tomasz Białecki
请提供测试仓库,其中包含最小的package.json、jest配置和这两个简单的tsx文件。 - Tomasz Białecki
请查看我的回答。https://stackoverflow.com/a/70270290/7387345 - sajadab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接