我們來先做一個component,模擬這個情況吧
import * as React from 'react';
import { useOutsideClick } from '../../src';
function OutsideClickSample() {
const [isOpen, setIsOpen] = React.useState(true);
const handleOutsideClick = () => {
setIsOpen(false);
};
const ref = useOutsideClick(handleOutsideClick);
return (
<section data-testid='outside'>
<div data-testid='inside' ref={ref}>{isOpen ? "Open" : "Closed"}</div>
</section>
)
}
export default OutsideClickSample
接下來我們要模擬
import React from "react";
import OutsideClickSample from "../example/component/OutsideClickSample"; // 请更正为你的组件路径
import { render, act } from '@testing-library/react';
describe("useOutsideClick", () => {
it('it should close when clicking outside', () => {
const { getByTestId, getByText } = render(<OutsideClickSample />);
const outSideSection = getByTestId("outside");
expect(getByText('Open')).toBeTruthy();
act(() => {
outSideSection.click();
});
expect(getByText('Closed')).toBeTruthy();
});
it('it should not close when clicking inside', () => {
const { getByTestId, getByText } = render(<OutsideClickSample />);
const inSide = getByTestId("inside");
expect(getByText('Open')).toBeTruthy();
act(() => {
inSide.click();
});
expect(getByText('Open')).toBeTruthy();
});
})
首先用render
將OutsideClickSample
模擬出來,使用兩個function,getByTestId
與getByText
他們一個可以取得有相同data-testid
的dom,一個可以取得相同內容的dom,靠這兩個方法我們就能跟以前一樣測試了