Vijay Thirugnanam
Learn React

Learn React

Close antd modal using React testing library

Vijay Thirugnanam's photo
Vijay Thirugnanam
·Aug 13, 2021·

2 min read

After learning React testing library, I set out an assignment for myself. The sequence of steps in my test are: Click a button to open antd Modal, verify if the modal is open, click on the close button on the top right corner ('X' icon) and verify if the modal closes.

My test case when translated into code looks like this:

test('Antd modal', async () => {
  render(<App />);
  const button = screen.getByRole('button', { name: /open antd/i });
  userEvent.click(button);
  const text = screen.getByText(/hello world/i);
  expect(text).toBeInTheDocument();
  const closeButton = screen.getByRole('button', { name: /close/i });
  userEvent.click(closeButton);
  await waitForElementToBeRemoved(() => screen.queryByText(/hello world/i));
});

The only step I was not sure about was on how to find the close button.

const closeButton = screen.getByRole('button', { name: /close/i });

The good thing is that it works. The icon has an aria-label of 'close'. So, we can query the button by name of close.

Screenshot 2021-08-13 at 5.39.07 PM.png

The code for the Modal that passes the test is quite simple:

<button onClick={handleAntdOpen}>Open antd modal</button>
<Modal
  visible={isAntdModalVisible}
  onOk={handleAntdCancel}
  onCancel={handleAntdCancel}
>
  <p>Hello world</p>
</Modal>

On checking the other frameworks, I found that bootstrap and material projects have similar aria-labels for the close button. But semantic does not have an aria-label for the button.

If you are not able to understand the code I have written or you are new to React testing library, I suggest having at a look at my article: Functional testing using React testing library and Jest .

 
Share this