unable to 运行 tests using react-testing-library "Cannot use import statement outside a module" 错误

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

这里是 Sandbox。可以通过在控制台中键入 npm run test -- -t "Store" 来触发该问题。将返回的错误是 Cannot use import statement outside a module,因为编译时 import React from "react"; 被添加到 util\store.test.tsx,原因我不明白。

只有在使用来自 react-testing-library

的导入(和 jsx)时才会遇到错误

我已经尝试了列出的所有建议 here 但没有任何效果。

我的 jest.config.ts 是;

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

babel.config.js是;

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

考虑到我的项目中使用的特定库的交互,我认为这是一个有点独特的错误,这就是为什么其他建议无法解决该问题的原因。

  1. JSX 模式更改为 "jsx": "react" for tsconfig.json.

  2. 添加ts-jest

  3. 像这样修改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"

测试结果:

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

测试环境设置正确,但您的测试用例失败。

CodeSandbox

由于未知原因,我的 babel.config.js 文件似乎有问题(原始问题中未提供,抱歉)

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

这最初是为了让 TypescriptNext.js 中工作而设置的,但不需要并且会破坏 Jest。删除文件有效,但是,我已将其设置为;

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

preset-env 有问题,因为删除该行专门修复了错误。