0

During developing vite react project I got a problem with react testing library or jest. I try to test async user fetching function, but jest is throwing an error

"Jest encountered an unexpected token"

&&

"Cannot use import statement outside a module".

As it shows, the problem is in axios import. Here is a photo of error and an example of code:

enter image description here

Here is User component:

import axios from "axios";
import React, { useEffect, useState } from "react";

const Users = () => {
  const [users, setUsers] = useState([]);
  const fetchUsers = async () => {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/users"
    );
    setUsers(response.data);
  };
  useEffect(() => {
    fetchUsers();
  }, []);
  return (
    <ul>
      {users.map((user) => (
        <li data-testid="user-item" key={user.id}> {user.name}</li>
      ))}
    </ul>
  );
};

export default Users;

Here is test file:

import {  render, screen } from "@testing-library/react";
import axios from "axios";

import Users from "./Users";

jest.mock('axios');
describe("users", () => {
  let response; 
  beforeEach(() => {
    response = {
      data: [
        {
          id: 1,
          name: "Leanne Graham",
        },
        {
          id: 2,
          name: "Ervin Howell",
        },
        {
          id: 3,
          name: "Clementine Bauch",
        },
      ],
    };
  });

  test("fetching users", async () => {
    axios.get.mockReturnValue(response);
    render(<Users/>)
    const users = await screen.findAllByTestId('user-item');
    expect(users.length).toBe(3)
  });
});

I have no idea what to do (((

burnsi
  • 6,194
  • 13
  • 17
  • 27

0 Answers0