dimanche 1 novembre 2020

React test failing even though debug is showing right output

Here's my component:

import React, { useState, useEffect } from "react";
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;

Here's my test:

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.

Aucun commentaire:

Enregistrer un commentaire