简体   繁体   English

无法使用 react-testing-library 运行测试“无法在模块外使用 import 语句”错误

[英]unable to run tests using react-testing-library "Cannot use import statement outside a module" error

here is a Sandbox .这是一个沙盒 the issue can be triggered by typing npm run test -- -t "Store" into the console.该问题可以通过在控制台中输入npm run test -- -t "Store"来触发。 The error that will be returned is Cannot use import statement outside a module because when compiled import React from "react";将返回的错误是Cannot use import statement outside a module because when compiled import React from "react"; is being added to util\store.test.tsx for reasons I don't understand.由于我不明白的原因,被添加到util\store.test.tsx中。

The error is only encountered when using imports (and jsx) from react-testing-library仅在使用react-testing-library中的导入(和 jsx)时才会遇到该错误

I have tried every suggestion listed here and nothing works.我已经尝试了这里列出的所有建议,但没有任何效果。

my jest.config.ts is;我的jest.config.ts是;

export default {
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8"
}

and babel.config.js is;babel.config.js是;

module.exports = {
    presets: [
      'next/babel',
      ['@babel/preset-env', {targets: {node: 'current'}}],
      '@babel/preset-typescript'
    ]
  }; 

I believe this is a somewhat unique error given interactions of specific libaries used in my project which is why other suggestions have not be able to resolve the issue.鉴于我的项目中使用的特定库的交互,我认为这是一个有点独特的错误,这就是为什么其他建议无法解决该问题的原因。

  1. Change JSX mode to "jsx": "react" for tsconfig.json .tsconfig.jsonJSX模式更改为"jsx": "react"

  2. Add ts-jest package添加ts-jest package

  3. Modify the jest.config.ts like this:像这样修改jest.config.ts

export default {
  preset: "ts-jest/presets/js-with-ts",
  testEnvironment: "jsdom",
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8"
}
  1. npm run test -- -t "Store"

Test result:测试结果:

sandbox@sse-sandbox-91opf:/sandbox$ npm run test -- -t "Store"

> music-quiz@0.1.0 test /sandbox
> jest "-t" "Store"

 FAIL  util/store.test.tsx (32.906 s)
  ● Store: › Should work

    TestingLibraryElementError: Unable to find an accessible element with the role "h1"

    Here are the accessible roles:

      heading:

      Name "":
      <h1 />

      --------------------------------------------------

    Ignored nodes: comments, <script />, <style />
    <body>
      <div>
        <h1 />
      </div>
    </body>

       6 |   it("Should work", () => {
       7 |     render(<h1></h1>);
    >  8 |     expect(screen.getAllByRole("h1")).toBeInTheDocument();
         |                   ^
       9 |   });
      10 |   it("definitely work", () => {
      11 |     expect(true).toBe(true);

      at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:38:19)
      at node_modules/@testing-library/dom/dist/query-helpers.js:90:38
      at node_modules/@testing-library/dom/dist/query-helpers.js:130:15
      at Object.<anonymous> (util/store.test.tsx:8:19)

----------|---------|----------|---------|---------|------------------------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|------------------------------------
All files |   36.17 |      100 |       0 |   36.17 |
 maths.ts |   11.11 |      100 |       0 |   11.11 | 1-5,7-9
 notes.ts |   37.87 |      100 |       0 |   37.87 | ...46,63-94,98-111,113-116,118-132
----------|---------|----------|---------|---------|------------------------------------
Test Suites: 1 failed, 2 skipped, 1 of 3 total
Tests:       1 failed, 30 skipped, 1 passed, 32 total
Snapshots:   0 total
Time:        37.472 s, estimated 49 s
Ran all test suites with tests matching "Store".
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! music-quiz@0.1.0 test: `jest "-t" "Store"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the music-quiz@0.1.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/sandbox/.npm/_logs/2021-11-25T04_42_32_701Z-debug.log

Test environment setup correctly, but your test case failed.测试环境设置正确,但您的测试用例失败。

CodeSandbox 代码沙盒

for reasons unknown there seemed to be a problem with my babel.config.js file (not provided in the original questions, sorry)由于未知原因,我的babel.config.js文件似乎有问题(原始问题中未提供,抱歉)

module.exports = {
    presets: [
      'next/babel',
      ['@babel/preset-env', {targets: {node: 'current'}}],
      '@babel/preset-typescript'
    ]
  };  

This was originally put in place to make Typescript work in Next.js but wasn't needed and was breaking Jest .这最初是为了使TypescriptNext.js中工作而设置的,但不需要并且正在破坏Jest Deleting the file worked, however, i have since set it to;删除文件有效,但是,我已将其设置为;

module.exports = {
    "presets": [
        "next/babel"
    ],
    "plugins": []
}

It was a problem with preset-env as deleting that line specifically fixed the error. preset-env存在问题,因为删除该行专门修复了错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在反应应用程序中测试 Go JS PackedLayout 时开玩笑“无法在模块外使用导入语句”错误 - Jest "cannot use import statement outside a module" error when testing Go JS PackedLayout in react app 当我尝试在我的 React 应用程序中运行 npm 测试时出现错误“SyntaxError: Cannot use import statement outside a module” - The error "SyntaxError: Cannot use import statement outside a module" appears when I try to run npm test in my react application 无法在 Apache 中运行网站(不能在模块外使用 import 语句) - Cannot run website in Apache (Cannot use import statement outside a module) 使用带有反应测试库的玩笑来测试对象的属性时出错 - Error in testing the properties of object using jest with react-testing-library SyntaxError:不能在模块外使用 import 语句,如何使用 react-native-svg 为 Web 运行测试单元? - SyntaxError: Cannot use import statement outside a module, how to run test unit with react-native-svg for the Web? 使用react-testing-library时无法找到带有文本的元素:“myText”错误 - Unable to find an element with the text: “myText” error when using react-testing-library 导入 React = &#39;SyntaxError: 不能在模块外使用导入语句&#39; - Importing React = 'SyntaxError: Cannot use import statement outside a module' React 16: SyntaxError: 不能在模块外使用 import 语句 - React 16: SyntaxError: Cannot use import statement outside a module SyntaxError: 不能在模块外使用 import 语句——React - SyntaxError: Cannot use import statement outside a module — React 与 Firebase 反应:不能在模块外使用 import 语句 - React w/ Firebase: Cannot use import statement outside a module
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM