【问题标题】:React test case failing only when another test is present仅当存在另一个测试时才反应测试用例失败
【发布时间】:2020-11-02 07:56:28
【问题描述】:

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

第二个测试失败,因为它说我的模拟响应未定义。但是,当我删除第一个测试时,第二个测试通过了。如果我在运行测试时打印出组件中的响应,则表明我的模拟响应应该是这样的。我不知道这两个测试用例之间是否存在某种关系或发生了什么。

谁能帮助我了解发生了什么以及为什么?谢谢。

【问题讨论】:

    标签: reactjs axios jestjs react-testing-library


    【解决方案1】:

    据我了解,原因是第一次测试出现问题,导致第二次测试失败。

    我的意思是效果中的代码将从第 1 次测试运行到第 2 次测试,但是在第 2 次测试在这一行运行的同时发生了错误:

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

    简而言之,要解决此问题,您可能必须在运行第二次测试之前清理所有内容,或者只是模拟以在第一次测试中具有价值以避免异常:

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

    【讨论】:

    • 谢谢,我终于明白了。你是老板,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多