如何使用react-testing-library将数组作为道具进行单元测试

谷仓猫头鹰

您如何将模拟道具与包装器组件道具匹配,我有点困惑。我知道怎么用酶开玩笑。但是不确定如何使用react-testing-library做到这一点。

我正在尝试将props.comments匹配到包装器:

const commentList = render(<CommentList {...props} />);

我应该检查什么?我想将prop注释与render / wrapper中的注释匹配吗?

我应该这样测试吗

 const commentList = render(<CommentList comments={props.comments}/>);
 expect(commentList).toHaveLength(2)

在数组中测试模拟项的正确方法是什么?

CommentList.test.tsx

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 { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList).toBeInTheDocument();
    });
});

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 key={i}>
                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
            </div>
        ));
    };
    console.log(ref);
    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}>
                            <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>;
弗洛里安·莫托(Florian Motteau)

您应该对注释列表中呈现的视觉元素进行测试。如果您的组件应呈现注释主体,则可以执行以下操作:

const rtl = render(<CommentList comments={props.comments}/>);

// test that both comments bodies are present in DOM
expect(rtl.getByText('firstCommentBody').toBeTruthy();
expect(rtl.getByText('secondCommentBody').toBeTruthy();

// or testing number of individual comment, assuming they are in li.comment, wrapped in a div with data-testid=comment-wrapper
expect(rtl.getByTestId('comment-wrapper').querySelectorAll('li.comment').length).toEqual(2);

React-testing-library像真实用户一样促进测试:检查打印的字符串,元素数,标签,占位符,角色...

只是问问自己:我期望在屏幕上看到什么?回答此问题时编写测试。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何发送POST请求的multipart / form-data字段作为数组进行单元测试?

如何使用http作为依赖项进行单元测试

您如何使用Jest和react-testing-library测试元素的不存在?

如何使用react-testing-library测试react-select

如何在React Native中使用TypeScript模拟React Navigation的导航道具进行单元测试?

将道具发送到React组件以进行Jest单元测试

使用React,Jest,React-Testing-Library测试失败的案例

使用react-testing-library测试react-hotkeys

如何在Jest和react-testing-library中使用react-hook

使用react-testing-library测试mxGraph

如果您正在使用React Testing Library / Enzyme的mount函数,它仍然是“单元测试”吗?

如何在用react-testing-library和jest完成的单元测试中启用react-i18n转换文件?

使用react-testing-library进行测试卸载

如何使用jest和react-testing-library测试上下文提供的功能?

使用react-testing-library测试组件是否使用正确的道具进行渲染

使用react-testing-library对样式化组件的直接子元素进行单元测试时,“在传递的组件上找不到样式规则”

如何通过Jest和react-testing-library测试useRef?

如何使用react-testing-library测试由其他组件组成的组件?

如何使用react testing库对父组件中子组件的渲染进行单元测试?

如何使用Jest和react-testing-library测试react-dropzone?

如何使用react-testing-library对进行异步数据加载的组件进行快照测试?

如何在React Testing Library(RTL)中测试特定模块

如何使用React Testing Library测试已记忆组件的回调?

如何使用 react-testing-library 测试 DOM 节点的外观

如何在使用 react-testing 库进行测试时渲染两个组件?

React-Query - 使用 react-testing-library 进行单元测试

如何使用 react-testing-library 测试带有动作重定向的表单

如何通过正确的道具进行酶单元测试?

如何使用 @testing-library/user-event 版本 14 在 React 中测试 `onKeyDown` 属性?