Reactjs 使用react测试库测试依赖于状态的条件呈现
测试依赖初始状态进行条件呈现的组件的方法是什么 例如,Reactjs 使用react测试库测试依赖于状态的条件呈现,reactjs,react-testing-library,Reactjs,React Testing Library,测试依赖初始状态进行条件呈现的组件的方法是什么 例如,showLessFlag依赖于状态,而react测试库中的测试状态则适得其反 那么我如何在CommentList组件中测试这个条件呢 {showLessFlag === true ? ( // will show most recent comments below showMoreComments() ) : ( <Fragment> {/* filter based on first c
showLessFlag
依赖于状态,而react测试库中的测试状态则适得其反
那么我如何在CommentList
组件中测试这个条件呢
{showLessFlag === true ? (
// will show most recent comments below
showMoreComments()
) : (
<Fragment>
{/* filter based on first comment, this shows by default */}
{filterComments.map((comment, i) => (
<div key={i} className="comment">
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
))}
</Fragment>
)}
{showLessFlag===true(
//将在下面显示最新的评论
showMoreComments()
) : (
{/*基于第一条注释的过滤器,默认情况下显示*/}
{filterComments.map((注释,i)=>(
))}
)}
是否应该像下面这样进行测试
it("should check more comments", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-show-more");
expect(commentList).toBeNull();
});
it(“应该检查更多注释”,()=>{
const{getByTestId}=render();
const commentList=getByTestId(“注释显示更多”);
expect(commentList.toBeNull();
});
但是我得到这个错误是因为条件渲染
TestingLibraryElement错误:无法通过以下方式找到元素:
[data testid=“comment show more”]
CommentList.tsx
import React, { Fragment, useState, Ref } from "react";
import Grid from "@material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";
function CommentList(props: any, ref: Ref<HTMLDivElement>) {
const [showMore, setShowMore] = useState<Number>(2);
const [openModal, setOpenModal] = useState(false);
const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
const the_comments = props.comments.length;
const inc = showMore as any;
const min = Math.min(2, the_comments - inc);
const showComments = (e) => {
e.preventDefault();
if (inc + 2 && inc <= the_comments) {
setShowMore(inc + 2);
setShowLessFlag(true);
} else {
setShowMore(the_comments);
}
};
const handleClickOpen = () => {
setOpenModal(true);
};
const handleCloseModal = () => {
setOpenModal(false);
};
const showLessComments = (e) => {
e.preventDefault();
setShowMore(2);
setShowLessFlag(false);
};
const isBold = (comment) => {
return comment.userId === props.userId ? 800 : 400;
};
// show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
const filterComments = props.comments
.slice(0)
.sort((a, b) => {
const date1 = new Date(a.createdAt) as any;
const date2 = new Date(b.createdAt) as any;
return date2 - date1;
})
.slice(0, inc)
.reverse();
const showMoreComments = () => {
return filterComments.map((comment, i) => (
<div data-testid="comment-show-more" key={i} className="comment">
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
));
};
return (
<Grid data-testid="comment-list-div">
<Fragment>
<div style={{ margin: "30px 0px" }}>
{props.comments.length > 2 ? (
<Fragment>
{min !== -1 && min !== -2 ? (
<Fragment>
{min !== 0 ? (
<OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>
) : (
<OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
Show Less Comments
</OurSecondaryButton>
)}
</Fragment>
) : (
<OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
Show Less Comments
</OurSecondaryButton>
)}
</Fragment>
) : null}
</div>
</Fragment>
{showLessFlag === true ? (
// will show most recent comments below
showMoreComments()
) : (
<Fragment>
{/* filter based on first comment */}
{filterComments.map((comment, i) => (
<div key={i} className="comment">
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
))}
</Fragment>
)}
</Grid>
);
}
export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;
import "@testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "@testing-library/react";
const props = {
user: {},
postId: null,
userId: null,
currentUser: {},
ref: {
current: undefined,
},
comments: [
{
author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
comment_body: "fsfsfsfsfs",
createdAt: "2020-05-27T14:32:01.682Z",
gifUrl: "",
id: 520,
postId: 28,
updatedAt: "2020-05-27T14:32:01.682Z",
userId: 9,
},
{
author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
comment_body: "fsfsfsfsfs",
createdAt: "2020-05-27T14:32:01.682Z",
gifUrl: "",
id: 519,
postId: 27,
updatedAt: "2020-05-27T14:32:01.682Z",
userId: 10,
},
],
deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
it("should render <CommentList/>", () => {
const commentList = render(<CommentList {...props} />);
expect(commentList).toBeTruthy();
});
it("should render first comment", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-list-div");
expect(commentList.firstChild).toBeTruthy();
});
it("should render second child", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-list-div");
expect(commentList.lastChild).toBeTruthy();
});
it("should check comments", () => {
const rtl = render(<CommentList {...props} />);
expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
expect(rtl.getByTestId("comment-list-div").querySelectorAll(".comment").length).toEqual(2);
});
it("should match snapshot", () => {
const rtl = render(<CommentList {...props} />);
expect(rtl).toMatchSnapshot();
});
it("should check more comments", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-show-more");
expect(commentList).toBeNull();
});
});
import React,{Fragment,useState,Ref}来自“React”;
从“@material ui/core/Grid”导入网格;
从“../../../common/OurSecondaryButton”导入OurSecondaryButton;
从“./CommentListContainer/CommentListContainer”导入CommentListContainer;
功能注释列表(道具:任意,参考:参考){
const[showMore,setShowMore]=useState(2);
const[openModal,setOpenModal]=useState(false);
const[showLessFlag,setShowLessFlag]=useState(false);
const the_comments=props.comments.length;
const inc=任何情况下的showMore;
const min=Math.min(2,the_comments-inc);
const showcoments=(e)=>{
e、 预防默认值();
如果(inc+2&&inc){
SetOpenModel(真);
};
常量handleCloseModal=()=>{
SetOpenModel(假);
};
const showLessComments=(e)=>{
e、 预防默认值();
setShowMore(2);
setShowLessFlag(假);
};
常量isBold=(注释)=>{
返回comment.userId==props.userId?800:400;
};
//按“最近”显示评论,并在底部显示最新的评论,前面的评论就在最新的评论之前。
const filterComments=props.comments
.slice(0)
.排序((a,b)=>{
const date1=新日期(a.createdAt),如有;
const date2=新日期(b.createdAt),如有;
返回日期2-日期1;
})
.slice(0,inc)
.reverse();
const showMoreComments=()=>{
返回filterComments.map((注释,i)=>(
));
};
返回(
{props.comments.length>2(
{min!=-1&&min!=-2(
{min!==0(
showComments(e)}component=“span”color=“secondary”>
查看{min!=-1&&min!=-2?min:0}更多评论
) : (
showLessComments(e)}component=“span”color=“secondary”>
少发表评论
)}
) : (
showLessComments(e)}component=“span”color=“secondary”>
少发表评论
)}
):null}
{showlesFlag===真(
//将在下面显示最新的评论
showMoreComments()
) : (
{/*基于第一条注释的过滤器*/}
{filterComments.map((注释,i)=>(
))}
)}
);
}
将默认React.forwardRef(CommentList)导出为React.RefForwardingComponent;
CommentList.test.tsx
import React, { Fragment, useState, Ref } from "react";
import Grid from "@material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";
function CommentList(props: any, ref: Ref<HTMLDivElement>) {
const [showMore, setShowMore] = useState<Number>(2);
const [openModal, setOpenModal] = useState(false);
const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
const the_comments = props.comments.length;
const inc = showMore as any;
const min = Math.min(2, the_comments - inc);
const showComments = (e) => {
e.preventDefault();
if (inc + 2 && inc <= the_comments) {
setShowMore(inc + 2);
setShowLessFlag(true);
} else {
setShowMore(the_comments);
}
};
const handleClickOpen = () => {
setOpenModal(true);
};
const handleCloseModal = () => {
setOpenModal(false);
};
const showLessComments = (e) => {
e.preventDefault();
setShowMore(2);
setShowLessFlag(false);
};
const isBold = (comment) => {
return comment.userId === props.userId ? 800 : 400;
};
// show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
const filterComments = props.comments
.slice(0)
.sort((a, b) => {
const date1 = new Date(a.createdAt) as any;
const date2 = new Date(b.createdAt) as any;
return date2 - date1;
})
.slice(0, inc)
.reverse();
const showMoreComments = () => {
return filterComments.map((comment, i) => (
<div data-testid="comment-show-more" key={i} className="comment">
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
));
};
return (
<Grid data-testid="comment-list-div">
<Fragment>
<div style={{ margin: "30px 0px" }}>
{props.comments.length > 2 ? (
<Fragment>
{min !== -1 && min !== -2 ? (
<Fragment>
{min !== 0 ? (
<OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>
) : (
<OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
Show Less Comments
</OurSecondaryButton>
)}
</Fragment>
) : (
<OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
Show Less Comments
</OurSecondaryButton>
)}
</Fragment>
) : null}
</div>
</Fragment>
{showLessFlag === true ? (
// will show most recent comments below
showMoreComments()
) : (
<Fragment>
{/* filter based on first comment */}
{filterComments.map((comment, i) => (
<div key={i} className="comment">
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
))}
</Fragment>
)}
</Grid>
);
}
export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;
import "@testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "@testing-library/react";
const props = {
user: {},
postId: null,
userId: null,
currentUser: {},
ref: {
current: undefined,
},
comments: [
{
author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
comment_body: "fsfsfsfsfs",
createdAt: "2020-05-27T14:32:01.682Z",
gifUrl: "",
id: 520,
postId: 28,
updatedAt: "2020-05-27T14:32:01.682Z",
userId: 9,
},
{
author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
comment_body: "fsfsfsfsfs",
createdAt: "2020-05-27T14:32:01.682Z",
gifUrl: "",
id: 519,
postId: 27,
updatedAt: "2020-05-27T14:32:01.682Z",
userId: 10,
},
],
deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
it("should render <CommentList/>", () => {
const commentList = render(<CommentList {...props} />);
expect(commentList).toBeTruthy();
});
it("should render first comment", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-list-div");
expect(commentList.firstChild).toBeTruthy();
});
it("should render second child", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-list-div");
expect(commentList.lastChild).toBeTruthy();
});
it("should check comments", () => {
const rtl = render(<CommentList {...props} />);
expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
expect(rtl.getByTestId("comment-list-div").querySelectorAll(".comment").length).toEqual(2);
});
it("should match snapshot", () => {
const rtl = render(<CommentList {...props} />);
expect(rtl).toMatchSnapshot();
});
it("should check more comments", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-show-more");
expect(commentList).toBeNull();
});
});
import“@testinglibrary/jest-dom”;
从“React”导入React,{Ref};
从“/CommentList”导入CommentList;
从“@testing library/react”导入{render,getByText,queryByText,getAllByTestId};
常量道具={
用户:{},
posted:null,
userId:null,
当前用户:{},
参考:{
当前:未定义,
},
评论:[
{
作者:{用户名:“谷仓猫头鹰”,格雷瓦塔:https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png,bio:null},
评论正文:“FSFS”,
创建日期:“2020-05-27T14:32:01.682Z”,
gifull:“,
id:520,
职位:28,
更新日期:“2020-05-27T14:32:01.682Z”,
用户ID:9,
},
{
作者:{用户名:“谷仓猫头鹰”,格雷瓦塔:https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png,bio:null},
评论正文:“FSFS”,
创建日期:“2020-05-27T14:32:01.682Z”,
gifull:“,
身份证号码:519,
职位:27,
更新日期:“2020-05-27T14:32:01.682Z”,
用户ID:10,
},
],
deleteComment:jest.fn(),
};
描述(“应该呈现”,()=>{
它(“应该呈现”,()=>{
const commentList=render();
expect(commentList.toBeTruthy();
});
它(“应该呈现第一条注释”,()=>{
const{getByTestId}=render();
const commentList=getByTestId(“注释列表div”);
expect(commentList.firstChild).to
<OurSecondaryButton
onClick={(e) => showLessComments(e)}
data-testid="_test-show-less"
component="span"
color="secondary"
>
Show Less Comments
</OurSecondaryButton>
it("should trigger showLessComments ", () => {
const { getByTestId } = render(<CommentList {...props} />);
const showLessButton = getByTestId("__test-show-less");
fireEvent.click(showLessButton);
expect(...) // whatever to be called, check for the existence of a div tag, or whatever you want
});