如何使React Component和Axios通过测试?

xdnvmnnf  于 2022-11-23  发布在  iOS
关注(0)|答案(1)|浏览(105)

由于在React项目中使用Axios,测试失败。
App.test.tsx

import React from 'react';
import { render } from '@testing-library/react';
import App from './App';

test('renders the', () => {
  const { getByText, getByRole } = render(
      <App />
  );
  
  expect(getByRole("button", {name: "Generate"})).toBeDisabled();
});

ApiService.ts

import axios from "axios";

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "type": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

然而,当我用“npm test”运行测试时,我得到以下失败的结果。
终点站
Terminal Screen

SyntaxError: Cannot use import statement outside a module

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

      at Runtime.createScriptFromCode (node_modules/react-scripts/node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/services/ApiService.ts:1:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        17.563 s
Ran all test suites related to changed files.

我怎样才能通过考试?如果你知道的话,请帮助我。
How to resolve "Cannot use import statement outside a module" in jest我按照这篇文章中的答案,但我只是得到了一个不同类型的错误,如下所示。

> jest

 FAIL  src/App.test.tsx
  ● Test suite failed to run

    error TS5025: Unknown compiler option 'type'. Did you mean 'types'?

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

dgsult0t1#

要解决此问题,请转到tsconfig.json文件并滚动到模块部分。
您应该在模块部分下看到一个类似以下的特定规则:

/* Modules */
"module": "esnext"

要解决此问题,请将值“esnext”更改为“commonjs”。
这就是:

/* Modules */
"module": "commonjs"

相关问题