繁体   English   中英

fireEvent 正在调用 Found multiple elements by: data-testid error in react-testing-library

[英]fireEvent is calling Found multiple elements by: data-testid error in react-testing-library

我通过使用"show_more_button"找到带有data-testid的按钮来调用 function

<OurSecondaryButton test={"show_more_button"} onClick={(e) => showComments(e)} component="span" color="secondary">
    View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>

显示评论

const showComments = (e) => {
  e.preventDefault();
  if (inc + 2 && inc <= the_comments) {
     setShowMore(inc + 2);
     setShowLessFlag(true);
  } else {
     setShowMore(the_comments);
  }
};

呈现这个

const showMoreComments = () => {
    return filterComments.map((comment, i) => (
        <div data-testid="comment-show-more" key={i}>
            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
        </div>
    ));
};

并在执行 fireEvent 时调用 function 这很好但是,我收到错误:

TestingLibraryElementError:通过以下方式找到多个元素:[data-testid =“comment-show-more”]

 (If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).

只有一个 data-testid 带有“comment-show-more”,我仔细检查了一下,我猜这个 function 一定在同一个测试中被多次触发,我不确定..

评论列表.test.tsx

   it("should fire show more action", () => {
      const { getByTestId } = render(<CommentList {...props} />);
      const showMore = getByTestId("show_more_button");
      fireEvent.click(showMore);
      expect(getByTestId("comment-show-more").firstChild).toBeTruthy();
   });

CommentList.test.tsx(完整代码)

import "@testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId, fireEvent } from "@testing-library/react";
import { Provider } from "react-redux";
import { store } from "../../../store";

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,
        },
        {
            author: { username: "barnowl2", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 518,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 11,
        },
    ],
    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 { queryByTestId } = render(<CommentList {...props} />);
        const commentList = queryByTestId("comment-show-more");
        expect(commentList).toBeNull();
    });

    it("should fire show more action", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const showMore = getByTestId("show_more_button");
        fireEvent.click(showMore);
        expect(getByTestId("comment-show-more").firstChild).toBeTruthy();
    });
});
  • 尝试在每次测试后清理 DOM

 import { cleanup } from '@testing-library/react' // Other import and mock props describe("Should render <CommentList/>", () => { afterEach(cleanup) // your test }

注意:您有filterComments.map所以确保filterComments有一项。

采用

getAllByTestId

例子:

await waitFor(() => userEvent.click(screen.getAllByTestId('serviceCard')[0]));

有点晚了,但这可能对某人有帮助:

我可以看到您正在使用可能返回多个子项的迭代器,如果您想以不同的方式解决问题,请在定义data-testid标记时为每个子项添加一个文字键:

const showMoreComments = () => {
    return filterComments.map((comment, i) => (
        <div data-testid={`comment-show-more-test-key-${i}`} key={i}>
            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
        </div>
    ));
};

可以通过使用getAllByTestId 来解决。

 it("should fire show more action", () => { const { getAllByTestId, getByTestId } = render(<CommentList {...props} />); const showMore = getAllByTestId("show_more_button")[0]; fireEvent.click(showMore); expect(getByTestId("comment-show-more").firstChild).toBeTruthy(); });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM