【发布时间】: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