【问题标题】:React-testing-library show error because of axios由于 axios,React-testing-library 显示错误
【发布时间】:2022-12-05 19:14:02
【问题描述】:

在 react with typescript 上学习单元测试,在导入 axios 时测试失败时遇到错误。 screenshot error in the terminal](https://i.stack.imgur.com/dFxJU.png)

代码组件

import axios from "axios";
import React, { FC, useEffect, useState } from "react";
import { IUser } from "../../types/IUsers";

const Users: FC = () => {
  const [users, setUsers] = useState<IUser[]>([]);
  useEffect(() => {
    getUsers();
  }, [users]);

  const getUsers = async () => {
    try {
      const response = await axios.get(
        "https://jsonplaceholder.typicode.com/users/"
      );
      const res = response.data;
      setUsers(res);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <div data-testid="users-wrapper">
      {users.map((user) => (
        <div>{user.name}</div>
      ))}
    </div>
  );
};

export default Users;

代码测试

import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Users from "./Users";
import axios from "axios";

jest.mock("axios");
describe("Testing user component", () => {
  test("Show title", () => {
    render(<Users />);
    const usersWrapper = screen.getByTestId("users-wrapper");
    expect(usersWrapper).toBeInTheDocument();
  });
});

尝试安装 axios 类型,创建 babel-config,创建 .babelrc,添加`

--transformIgnorePatterns \"node_modules/(?!axios)/\""

` 在 package-json 上。请帮帮我。

【问题讨论】:

  • 这看起来更像是关于使用仅在最新版本中可用的导入语句的 NodeJS 错误(我认为默认情况下禁用,除非您更改标志)。通常,当您测试使用 ESModules 编写的代码时,您需要将 import 转换为 require() 调用。我知道 ts-jest@swc/jest 可以做到这一点。

标签: reactjs typescript axios jestjs react-testing-library


【解决方案1】:

在 package.json 中添加以下内容并尝试:

"jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!axios)/"
    ]
  },

这为我解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-10
    • 2021-07-16
    • 2019-10-30
    • 2019-10-17
    • 2021-03-20
    • 1970-01-01
    • 2022-07-29
    • 2021-06-02
    相关资源
    最近更新 更多