1

Getting error on the line

import axios from 'axios';

in unit test case. Please help me - why am I getting this Axios error in unit test?

React component is:

const AwaitAsync2 = () => {
const [posts, setPosts] = useState(null);

useEffect(() => {
    postApi();
}, []);

const postApi = async () => {
    const {data} = await axios.get('https://jsonplaceholder.typicode.com/posts');
    setPosts(data);
}
return (
    <div>
        <h2>Await Async</h2>
        {
            posts !== null && (<div data-testid="post-list">
                {
                    posts.map((item, index) => {
                        return <div key={index}>
                            <h3>{item.title}</h3>
                            <p>{item.body}</p>
                        </div>
                    })
                }
            </div>)
        }
    </div>
)
}

Unit test case is

import { render, screen } from "@testing-library/react";
import AwaitAsync2 from "./aa2";

describe("Async Await 2 testing", () => {

it("API Testing", async () => {
    render(<AwaitAsync2 />);
    const data = await screen.findByTestId("post-list");
    expect(data).toBeInTheDocument();
});

});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Pradeep
  • 159
  • 2
  • 2
  • 7
  • jest doesn't know anything about things you import in your component. mock it. https://stackoverflow.com/questions/45016033/how-do-i-test-axios-in-jest – Badal Saibo Feb 11 '23 at 04:48

0 Answers0