在react中运行测试时导入语句错误

问题描述 投票:0回答:1

我在尝试为我的反应应用程序运行测试时收到导入语句错误。安装 JEST 后会发生这种情况。

我分享以下错误供您参考

 ● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • 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/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

C:\Users\Pos\Desktop\live-projects\git-lab\new-clone\chan\restaurant-pos-v1-react\node_modules\axios\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                  
            ^^^^^^

SyntaxError: Cannot use import statement outside a module

> 1 | import axios from "axios";
    | ^
  2 |
  3 | // import varaiable
  4 | import {

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
  at Object.<anonymous> (src/api/index.js:1:1)
  at Object.<anonymous> (src/actions/credit-sale/creditSale_CustomAction.js:1:1)
  at Object.<anonymous> (src/components/creditSale/creditSaleSearchBar.jsx:4:1)
  at Object.<anonymous> (src/pages/creditSale/creditSale.jsx:5:1) 
  at Object.<anonymous> (src/__test__/pages/creditSale/creditSale.test.js:2:1)
  at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
  at runJest (node_modules/@jest/core/build/runJest.js:404:19)    

测试套件:1 次失败,总共 1 次
测试:总共 0 次
快照: 共 0 个 时间:4.375秒 运行与更改的文件相关的所有测试套件。

reactjs unit-testing testing jestjs babeljs
1个回答
0
投票

这可能是由于缺少运行 ES 模块的 Jest 配置。默认情况下,Jest 会查找 CommonJs 模块,这就是为什么它可能无法读取您的

import
语句。请参阅以下链接来启动并运行

如何通过 jest 使用 ESM 测试?

https://gist.github.com/rstacruz/511f43265de4939f6ca729a3df7b001c

© www.soinside.com 2019 - 2024. All rights reserved.