reactjs - 创建 react 应用程序和 Jest — SyntaxError : Unexpected token import

标签 reactjs jestjs babeljs create-react-app

注意:我通过将 src/nod_modules 文件夹中的所有代码直接移至 src 文件夹并删除 src/node_modules 来修复此问题> 根据这个短线程:https://github.com/facebook/create-react-app/issues/4241

<小时/>

我正在使用 create-react-app,但运行 Jest 时遇到问题。

当我尝试将任何一个 React 组件导入到测试文件中时,yarn test 时出现错误:

Test suite failed to run

.../src/node_modules/common/ErrorMessage.js:1
({"Object.<anonymous>":function(
module,exports,require,__dirname,__filename,global,jest)
{import React from 'react'
^^^^^^

SyntaxError: Unexpected token import

这就是我的测试文件的样子:

// test.test.js

// attempting to import
import ErrorMessage from '../node_modules/common/ErrorMessage.js'

// dummy test
test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3)
})

但是,如果我位于 src 文件的根目录并导入 index.js,则不会引发错误。此时,index.js 导入的第一个文件中会抛出错误。例如:

test.test.js

import index from './index'

index.js

import React from 'react'
import { render } from 'react-dom'
import './style/index.css'
import LoginContainer from './node_modules/user/LoginContainer'
import NewUser from './node_modules/user/NewUser'
// etc.

终端输出

 FAIL  src/test.test.js
  ● Test suite failed to run

    /Users/hannahmccain/Desktop/DEV/expense-report/fullstack-expense-report/client/src/node_modules/user/LoginContainer.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React, { Component } from 'react'
                                                                                             ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
      at Object.<anonymous> (src/index.js:11:164)
      at Object.<anonymous> (src/test.test.js:3:14)

在 Jest 的上下文中,Babel 似乎无法正确编译 src/node_modules 中的文件。我只是不知道如何纠正它!任何见解将不胜感激。

仅供引用,Jest 应该可以与 create-react-app 一起开箱即用,我不想弹出。如果不弹出,我就无法进行我在其他地方看到的推荐的某些更改,例如更新我的 package.json 中的 Jest 设置。

最佳答案

为了跟进 @Himanshu Singh 的回答,通过将其添加到我的 package.json 中帮助我解决了这个错误。

{
  test: react-scripts test --transformIgnorePatterns \"node_modules/(?!ui-core)/\" --env=jsdom
}

关于reactjs - 创建 react 应用程序和 Jest — SyntaxError : Unexpected token import,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49616199/

相关文章:

javascript - 无法获取函数中 Usestate 的值

reactjs - 仅当文件类型更改时,react-file-viewer 才会重新渲染

javascript - GET 请求返回 index.html 文档而不是 json 数据

angular - '引用错误: define is not defined' when testing Angular app with jest using ApplicationInsights-js

jestjs - 在 IDE 或命令行中运行 E2E 测试

jestjs - Jest 在测试中未转译 ES6 模块(SyntaxError : Unexpected token export))

javascript - React Native Redux Reducer 不工作

javascript - Babel-preset-react 用三元运算符破坏条件 Array.map

javascript - 有人有将 NightWatch 与 TypeScript 一起使用的经验吗?

meteor - 获取babel在meteor中生成的程序