单击按钮时无法关闭React Bootstrap模态 - React Testing库

发布于 2025-02-11 03:37:45 字数 4256 浏览 1 评论 0原文

我正在使用React Testing库来测试单击按钮时的模态,从React Bootstrap中关闭。 由于某种原因,我无法进行测试,因为它的结果不断显示模态元素。

这是我的反应组件:

    import { HashLink as Link } from "react-router-hash-link";
    import { Modal } from "react-bootstrap";
    import styles from "./PledgeSubmittedModalCard.module.scss";
    import iconCheck from "../../icons/icon-check.svg";

    export const PledgeSubmittedModalCard = ({
      onCloseClick,
      confirmationPledgeText,
    }) => {
      return (
        <Modal
          show
          backdrop="static"
          keyboard={false}
          centered
          dialogClassName={styles.pledgesModal}
          data-testid="pledge-submitted-modal"
          onHide={onCloseClick}
        >
          <div className={styles.modalContainer}>
            <img
              className={styles.iconCheck}
              src={iconCheck}
              alt="completed action icon"
            />
            <h5 className={styles.sayThanks}>Thanks for your support!</h5>
            <p role="paragraph" className={styles.confirmationText}>
              {confirmationPledgeText}
            </p>
            <Link to="#top">
              <button onClick={onCloseClick} className={styles.confirmationBtn}>
                Got it
              </button>
            </Link>
          </div>
        </Modal>
      );
    };

这里进行了我的测试:

    import {
      prettyDOM,
      render,
      screen,
    } from "@testing-library/react";
    import userEvent from "@testing-library/user-event";
    import { BrowserRouter } from "react-router-dom";
    import { PledgeSubmittedModalCard } from "../index";

    const onClickMock = jest.fn();

    const MockPledgeSubmittedModalCard = () => {
      return (
        <BrowserRouter>
          <PledgeSubmittedModalCard onCloseClick={onClickMock} />
        </BrowserRouter>
      );
    };

    describe("PledgeSubmittedModalCard", () => {
      it("Should close modal when button clicked", () => {
        render(<MockPledgeSubmittedModalCard />);
        const modalElement = screen.queryByTestId("pledge-submitted-modal");
        const buttonElement = screen.getByRole("button", {
          name: "Got it",
        });
        console.log(prettyDOM(modalElement));
        userEvent.click(buttonElement);
        // PASSED
        expect(onClickMock).toBeCalledTimes(1);
        // FAILED
        expect(modalElement).not.toBeInTheDocument();
      });
    });

最后测试输出:

     ● PledgeSubmittedModalCard › Should close modal when button clicked

        expect(element).not.toBeInTheDocument()

        expected document not to contain element, found <div class="modal-dialog pledgesModal modal-dialog-centered" data-testid="pledge-submitted-modal"><div class="modal-content"><div class="modalContainer"><img alt="completed action icon" class="iconCheck" src="icon-check.svg" /><h5 class="sayThanks">Thanks for your support!</h5><p class="confirmationText" role="paragraph" /><a href="/#top"><button class="confirmationBtn">Got it</button></a></div></div></div> instead

          38 |     expect(onClickMock).toBeCalledTimes(1);
          39 |     // expect(modalElement).toBeNull();
        > 40 |     expect(modalElement).not.toBeInTheDocument();
             |                              ^
          41 |   });
          42 | });
          43 |

          at Object.<anonymous> (src/components/PledgeSubmittedModalCard/__test__/PledgeSubmittedModalCard.test.js:40:30)


    Test Suites: 1 failed, 7 skipped, 1 of 8 total
    Tests:       1 failed, 26 skipped, 1 passed, 28 total
    Snapshots:   0 total
    Time:        3.544 s, estimated 4 s
    Ran all test suites with tests matching "PledgeSubmittedModalCard".

我试图用期望(modalelement).not.tobeIndocument(),, Expect(Modalelement)。 tobenull()和等待waitforelementtoberemaved((()=&gt; modalement),但它们都没有起作用。我还有什么可以尝试的吗?谢谢!

I am using React Testing Library to test that a modal, from React Bootstrap, closes when the button is clicked.
For some reason, I can't make the test pass, since the result of it keeps on showing the modal element.

Here is my React Component:

    import { HashLink as Link } from "react-router-hash-link";
    import { Modal } from "react-bootstrap";
    import styles from "./PledgeSubmittedModalCard.module.scss";
    import iconCheck from "../../icons/icon-check.svg";

    export const PledgeSubmittedModalCard = ({
      onCloseClick,
      confirmationPledgeText,
    }) => {
      return (
        <Modal
          show
          backdrop="static"
          keyboard={false}
          centered
          dialogClassName={styles.pledgesModal}
          data-testid="pledge-submitted-modal"
          onHide={onCloseClick}
        >
          <div className={styles.modalContainer}>
            <img
              className={styles.iconCheck}
              src={iconCheck}
              alt="completed action icon"
            />
            <h5 className={styles.sayThanks}>Thanks for your support!</h5>
            <p role="paragraph" className={styles.confirmationText}>
              {confirmationPledgeText}
            </p>
            <Link to="#top">
              <button onClick={onCloseClick} className={styles.confirmationBtn}>
                Got it
              </button>
            </Link>
          </div>
        </Modal>
      );
    };

Here it goes my test:

    import {
      prettyDOM,
      render,
      screen,
    } from "@testing-library/react";
    import userEvent from "@testing-library/user-event";
    import { BrowserRouter } from "react-router-dom";
    import { PledgeSubmittedModalCard } from "../index";

    const onClickMock = jest.fn();

    const MockPledgeSubmittedModalCard = () => {
      return (
        <BrowserRouter>
          <PledgeSubmittedModalCard onCloseClick={onClickMock} />
        </BrowserRouter>
      );
    };

    describe("PledgeSubmittedModalCard", () => {
      it("Should close modal when button clicked", () => {
        render(<MockPledgeSubmittedModalCard />);
        const modalElement = screen.queryByTestId("pledge-submitted-modal");
        const buttonElement = screen.getByRole("button", {
          name: "Got it",
        });
        console.log(prettyDOM(modalElement));
        userEvent.click(buttonElement);
        // PASSED
        expect(onClickMock).toBeCalledTimes(1);
        // FAILED
        expect(modalElement).not.toBeInTheDocument();
      });
    });

And finally the tests output:

     ● PledgeSubmittedModalCard › Should close modal when button clicked

        expect(element).not.toBeInTheDocument()

        expected document not to contain element, found <div class="modal-dialog pledgesModal modal-dialog-centered" data-testid="pledge-submitted-modal"><div class="modal-content"><div class="modalContainer"><img alt="completed action icon" class="iconCheck" src="icon-check.svg" /><h5 class="sayThanks">Thanks for your support!</h5><p class="confirmationText" role="paragraph" /><a href="/#top"><button class="confirmationBtn">Got it</button></a></div></div></div> instead

          38 |     expect(onClickMock).toBeCalledTimes(1);
          39 |     // expect(modalElement).toBeNull();
        > 40 |     expect(modalElement).not.toBeInTheDocument();
             |                              ^
          41 |   });
          42 | });
          43 |

          at Object.<anonymous> (src/components/PledgeSubmittedModalCard/__test__/PledgeSubmittedModalCard.test.js:40:30)


    Test Suites: 1 failed, 7 skipped, 1 of 8 total
    Tests:       1 failed, 26 skipped, 1 passed, 28 total
    Snapshots:   0 total
    Time:        3.544 s, estimated 4 s
    Ran all test suites with tests matching "PledgeSubmittedModalCard".

I have tried to assert with expect(modalElement).not.toBeInDocument(), expect(modalElement).toBeNull(), and await waitForElementToBeRemoved(() => modalElement), but none of them worked. Is there anything else I can try? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月竹挽风 2025-02-18 03:37:45

通过单击一个名为的按钮触发 oncloseclick 方法,将模态关闭,该方法是从父元组件传递的。

由于您只是将模拟功能作为道具传递,因此不会做任何事情。

&lt; pledgesubmittedModalCard onCloseClick = {onClickMock}/&gt;

如果要测试是否要测试模态,则必须传递一个真实的oncloseclick功能才能使其起作用。

The modal is closed by clicking a button named Got it and it triggers onCloseClick method, which is being passed as a prop from the parent component.

Since you are just passing a mock function as a prop, it won't do anything.

<PledgeSubmittedModalCard onCloseClick={onClickMock} />

If you want to test if modal is closed, you have to pass a real onCloseClick function to make it work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文