Consider I have this component
function RankDialog(props: any) {
const { visible = true, setVisible } = props;
return (
<Dialog
visible={visible}
className="rank-dialog"
scrollBoxClassName="rank-scroll-box"
alignBottom
noMargin
noContentPadding
onClose={() => {
setVisible(false);
}}
onCancel={() => {
setVisible(false);
}}
>
<Rank />
</Dialog>
);
}
on my unit test, it said I missed the coverage of these lines
onClose={() => {
setVisible(false);
}}
onCancel={() => {
setVisible(false);
}}
How to write the unit test just to check if the props is passing correctly. I searched google it said I have to trigger the click of close and cancel. Is there any different way, as I may not know what is the close and cancel button looks like in order to query it correctly.
I’m thinking just to write a test to check if the Dialog.props.onClose
is passed correctly.
I’m using @testing-library/react
2
Answers
You can use
jest.fn()
to create a mock function forsetVisible
, and then check if it has been called with the expected value whenonClose
andonCancel
are called. This way, you don’t need to worry about the implementation details of theDialog
component or querying the close and cancel buttons.You can pass a Jest mock function as the
setVisible
prop to the RankDialog component, allowing you to capture calls to the function and assert on them.These two test cases check if the setVisible function is called with the expected argument (false) when the "close" and "cancel" buttons are clicked. Using
@testing-library/user-event
to simulate user events is the recommended approach in the testing library ecosystem as mentioned here, as it is said to closely mimic real user interactions and ensure that the tests are closer to actual user behavior.In the first test case, the "close" button is queried using
screen.getByRole("button", { name: /close/i })
and a click is simulated on it usinguserEvent.click(closeBtn)
. Then, you use expect to assert that thesetVisible
function is called withfalse
as an argument.In the second test case, you do a similar action by querying for the "cancel" button.
screen.getByRole("button", { name: /cancel/i })
has been used to query for the button.This approach allows you to test the expected behavior of the RankDialog component without relying on the specific implementation details of the buttons’ appearance, which makes the tests more resilient to changes in the UI.