0

Learning unit-testing on the react with typescript, encountered an error when tests fall when importing axios. screenshot error in the terminal](https://i.stack.imgur.com/dFxJU.png)

Code component

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;

Code test

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();
  });
});

Tried install types for axios, create babel-config, create .babelrc, add `

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

` on the package-json. Help me please.

ARSync
  • 11
  • 1
  • 4
  • This looks more like an NodeJS error about using import statements which are only available in the latest versions (and I think disabled by default unless you change a flag). Usually when you are testing code written with ESModules you need to transform `import` into `require()` calls. I know that `ts-jest` and `@swc/jest` can do that. – ncpa0cpl Nov 04 '22 at 12:50
  • I personally use global mocks for axios, maybe this [answer](https://stackoverflow.com/a/74544749/20293448) will help you – Jérémy Rippert Dec 05 '22 at 12:22

2 Answers2

0

Add the following in package.json and try:

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

This fixed the issue for me.

sjsouvik
  • 113
  • 1
  • 8
-1

I use this pattern, and it's works for me too

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 09 '23 at 11:49