Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React test case failing only when another test is present

Post.jsx:

import axios from "axios";
const Post = ({ url }) => {
  const [data, setData] = useState(null);
  useEffect(() => {
    const sendReq = async () => {
      const res = await axios.get(url);
      setData(res.data);
    };
    sendReq();
  }, []);
  if (!data) {
    return <span data-testid="loading">"Loading...."</span>;
  }
  return (
    <div>
      <span data-testid="body">{data.body}</span>
    </div>
  );
};

export default Post;

Post.test.jsx:

import { cleanup, screen, render, waitFor } from "@testing-library/react";
import Post from "./Post";
import axios from "axios";
jest.mock("axios");

describe("Post component", () => {
  it("shows loading", () => {
    render(<Post url="/test"></Post>);
    expect(screen.getByTestId("loading")).toHaveTextContent(/loading/i);
    cleanup();
  });
  it("shows post", async () => {
    const resp = { data: { body: "COunter strike" } };
    axios.get.mockResolvedValue(resp);
    render(<Post url="/test"></Post>);
    await waitFor(() => screen.getByTestId("body"));
    screen.debug();
    expect(screen.getByTestId("body")).toHaveTextContent(/counter/i);
  });
});

The second test fails because it says that my mocked response is undefined. However, when i remove the first test, the second one passes. If my print out the response in the component while running the test, it shows my mocked response is how it should be. I don't know if there is some relationship between these 2 test cases or what is happening.

Can anyone help me understand what is going on and why? Thank you.

like image 289
Nabin Chaulagain Avatar asked Dec 22 '25 00:12

Nabin Chaulagain


1 Answers

From my understanding, the reason is the 1st test having problem as running causing the 2nd test getting failed.

I meant the code in the effect will run from this 1st test to 2nd test, but there is an error occurred at the same time the 2nd test is running at right this line:

const sendReq = async () => {
  const res = await axios.get(url);
  // res is undefined in the 1st test
  // so it won't read the data property, you might see this in your log terminal
  setData(res.data);
}

In short, to fix this issue you might have to cleanup everything prior to running the 2nd test or just mock to have value in 1st test to avoid exception:

it("shows loading", () => {
  // Mock to avoid exception
  axios.get.mockResolvedValue({ data: {} });
 
  render(<Post url="/test"></Post>);
  expect(screen.getByTestId("loading")).toHaveTextContent(/loading/i);
  
  // It can't help to stop async task in effect
  cleanup();
});
like image 103
tmhao2005 Avatar answered Dec 23 '25 15:12

tmhao2005



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!