reactjs - 测试套装因 "SyntaxError: Unexpected token ' export"' react typescript using jest 而失败

标签 reactjs typescript jestjs ts-jest react-typescript

我在我的 react-typescript 项目中设置了 jest 和 enzyme。在这个项目中我没有使用 babel。

我尝试运行基本组件并且运行良好。

之后我添加了另一个组件,并在此组件中添加了我们自定义的基于 react-typescript 的库 (cc-react-common-lib)。

当我包含 cc-react-common-lib 时,jest 抛出以下错误

语法错误:意外的 token “导出”

 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/convertcart/projects/intelli-blocks/node_modules/cc-react-common-lib/lib/index.js:1
    export { default as TableSpaced } from './general/table-spaced';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      1 | /* eslint-disable jsx-a11y/control-has-associated-label */
      2 | import React, { useState, useEffect } from 'react';
    > 3 | import {
        | ^
      4 |   TextField,
      5 |   useAjaxForm,
      6 |   Spacer,

过去 1 周我尝试解决这个错误,但我找不到任何解决方案

jest.config.js:

module.exports = {
  // The root of your source code, typically /src
  // `<rootDir>` is a token Jest substitutes
  roots: ['<rootDir>'],

  // Jest transformations -- this adds support for TypeScript
  // using ts-jest
  // transform: {
  //   "^.+\\.tsx?$": "ts-jest"
  // },
  preset: 'ts-jest',
  // maxConcurrency:30,
  // Runs special logic, such as cleaning up components
  // when using React Testing Library and adds special
  // extended assertions to Jest
  // setupFilesAfterEnv: [
  //   "@testing-library/react/cleanup-after-each",
  //   "@testing-library/jest-dom/extend-expect"
  // ],

  // Test spec file resolution pattern
  // Matches parent folder `__tests__` and filename
  // should contain `test` or `spec`.
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',

  // Module file extensions for importing
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  snapshotSerializers: ['enzyme-to-json/serializer'],
  setupFilesAfterEnv: ['<rootDir>/setupEnzyme.ts'],
};

setupEnzyme.js:

/* eslint-disable import/no-extraneous-dependencies */
import Enzyme from 'enzyme';
import ReactSixteenAdapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new ReactSixteenAdapter() });

更新:当我在 jest.confi.js 文件中添加以下行时

transform: {
    '^.+\\.tsx?$': 'babel-jest',
  },

出现以下错误消息:

● Test suite failed to run

    SyntaxError: /home/convertcart/projects/intelli-blocks/client/__tests__/editblock.test.tsx: Support for the experimental syntax 'jsx' isn't currently enabled (8:29):

       6 | console.log("Edit block test");
       7 | it('Renders and Simulates Click Event ', () => {
    >  8 |     const Wrapper = shallow(<EditBlock />);
         |                             ^
       9 |     const checkbox = () => Wrapper.find({ type: 'checkbox' });
      10 |     expect(checkbox().props().checked).toBe(false);
      11 |     checkbox().simulate('change', { target: { checked: true } });

    Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
    If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.

      at Parser._raise (../node_modules/@babel/parser/src/parser/error.js:60:45)
      at Parser.raiseWithData 

最佳答案

如果您通过代码编辑器插件运行测试,请尝试在编辑器中配置插件测试命令以确保插件执行正确的命令。

例如我正在使用 vscode、jestrunner 插件和 yarn 包管理器。所以我在我的工作区 settings.json 文件中包含了以下行:

{
    "jestrunner.jestCommand": "yarn react-scripts test"
}

同样的错误得到了解决。希望它对你有用:)

关于reactjs - 测试套装因 "SyntaxError: Unexpected token ' export"' react typescript using jest 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63827324/

相关文章:

javascript - ReactJS | onClick 的 Typescript 类型。 `onclick does not exist on type` x`

javascript - Uncaught ReferenceError : ReactDOM is not defined with bundle. js

javascript - 如何使用 Jest 模拟构造函数状态初始化

javascript - 使用回调对异步函数进行单元测试

javascript - 将动态参数传递给事件处理程序

javascript - React Native 更新状态中嵌套对象的单个属性

javascript - 为什么我无法使用 Typescript/node.js 导入模块?

typescript - 具有两个商店的 mapStateToProps 中未定义 Redux 状态

angular - 如何通过迭代 typescript 中的数组和标签中的组项目来填充菜单项?

javascript - 如何测试依赖于 setState 的未挂载 React 组件的方法?