【问题标题】:Jest.js and Create-react-app: I get "SyntaxError: Cannot use import statement outside a module" when running testJest.js 和 Create-react-app:运行测试时出现“语法错误:无法在模块外使用导入语句”
【发布时间】:2020-04-11 15:00:19
【问题描述】:

我的代码

App.test.js

import moment from "moment-timezone";

let result = moment().format();


describe("anything",()=>{
    it("should return a fail..or at least something",()=>{
        expect(result).toBe("wrong")
    })
})

我跑:

npx jestyarn 测试npm 测试

我明白了:

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

    /home/wktdev/Desktop/thing/workflow_magic_guest_app/src/App.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import moment from "moment-timezone";
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.586s
Ran all test suites.

貌似是这样的:https://github.com/facebook/jest/issues/9292

当我执行 npm ls jest 时,它说缺少依赖项。当我尝试手动安装它们时,它们没有安装,问题也没有解决。

UNMET DEPENDENCY react-scripts@2.1.5
  └── UNMET DEPENDENCY jest@23.6.0 

【问题讨论】:

  • 如果你运行 npm testyarn test 会发生什么
  • @Teneff 是的,它有效。可恶。大声笑
  • 我拥有的实例正在运行,我克隆了一个新实例,但它现在无法运行。当我执行 npm ls jest 时,它说缺少依赖项。当我尝试手动安装它们时,它不起作用。我将编辑查询以反映这一点。
  • 克隆 repo 后,您是否使用“npm install”安装了列出的依赖项?

标签: javascript jestjs create-react-app


【解决方案1】:

我根据开玩笑输出的消息弄清楚了。 jest 给出了删除 package.lock 文件、yarn.lock 并通过 yarn install 重新安装的说明。 我之前尝试过,我认为它不起作用,只是删除了玩笑,但我错了。它似乎工作 - 现在。

【讨论】:

    【解决方案2】:

    如果您手动添加 jest,请从 package.json 中删除 jest 依赖项并运行 npm installyarn install

    或者您可以运行npm testyarn test 来检查指令。

    【讨论】:

      【解决方案3】:

      要解决这个问题,您需要创建文件:./__tests__/setup.js 并输入:

      
      import { configure } from "enzyme";
      import Adapter from "enzyme-adapter-react-16";
      
      configure({ adapter: new Adapter() });
      
      

      之后你只需要运行:npm run test

      【讨论】:

      • 完全没有帮助
      猜你喜欢
      • 2020-05-30
      • 2022-11-17
      • 2022-01-02
      • 2021-02-21
      • 2022-06-10
      • 2021-07-02
      • 2021-05-20
      相关资源
      最近更新 更多