所以我有一个简单的组件,带有一个按钮,可以打开一个反应吐司模式。当用户单击 React-toastify 中内置的“关闭”按钮(X)时,模式将关闭。
现在我想为这个组件编写测试。 问题是我无法测试当用户单击关闭按钮时模式是否关闭。
这是我的代码。
MyComponent.js
import React, { useState } from "react";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
const MyComponent = () => {
const [isModalOpen, setIsModalOpen] = useState(false);
const handleOpenModal = () => {
if (!isModalOpen) {
toast.success("This is modal content.", {
autoClose: false,
closeOnClick: false,
onClose: () => setIsModalOpen(false), // Update state on close
});
setIsModalOpen(true);
}
};
return (
<div>
<button onClick={handleOpenModal}>Open Modal</button>
</div>
);
};
export default MyComponent;
MyComponent.test.js
import React from "react";
import { render, fireEvent, waitFor, act } from "@testing-library/react";
import MyComponent from "./MyComponent";
import { ToastContainer } from "react-toastify";
// Test: Clicking close button closes modal
test("clicking close button closes modal", async () => {
const { queryByText, getByRole } = render(
<>
<MyComponent />
<ToastContainer />
</>
);
const button = getByRole("button", { name: "Open Modal" });
act(() => {
fireEvent.click(button);
});
await waitFor(() => queryByText("This is modal content."));
const closeButton = getByRole("button", { name: "close" });
expect(closeButton).toBeInTheDocument();
act(() => {
fireEvent.click(closeButton);
});
expect(queryByText("This is modal content.")).toBeNull();
});
那么如何进行测试运行呢?
到目前为止你所做的一切都很好。模态关闭后,您可以使用
setTimeout
调用 expect
。
describe('MyComponent', () => {
it('Should close modal on clicking close', async () => {
const {getByRole, queryByText} = render(
<>
<MyComponent />
<ToastContainer />
</>
)
const button = getByRole('button')
fireEvent.click(button)
await waitFor(() => queryByText("This is modal content."))
const closeButton = getByRole("button", { name: "close" })
fireEvent.click(closeButton)
setTimeout(() => {
expect(queryByText("This is modal content.")).toBeNull();
}, 1)
})
})