2

I'm using react testing library to test my component built with FluentUI.

Here is link: https://codesandbox.io/s/keen-borg-2tqmj?file=/src/App.spec.js

The code is basically a pasted snippet of the example code of Dialog component from FluentUI docs site. The behavior that I'm testing is:

  1. User opens the dialog
  2. User clicks outside of the dialog
  3. onDimiss prop of the component should be fired.

It works when I'm playing with it manually however it seems that I failed to simulate a click outside of the component with testing library.

I tried using userEvent.click(document.body) as mentioned in this post but got no luck

Does anyone has any idea how to make test work?

Shi Cheng
  • 117
  • 3
  • 9

1 Answers1

2

It is not working because the Dialog component is not listening for the onClick event on the body, so what you need to do in this case is to find the actual element that is being clicked, observing the dom you'll find that the overlay is a div with some overlay classes on it.

        <div
          class="ms-Modal is-open ms-Dialog root-94"
          role="document"
        >
          <div
            aria-hidden="true"
            class="ms-Overlay ms-Overlay--dark root-99"
          />

The problem now is to find a way to select it. Unfortunately, you cannot select elements in RTL by their className, so you need to use another selector; in this case, we can get the parent element by the role and then access the first child.

    const onDismiss = jest.fn();
    const { getByRole } = render(<App onDismiss={onDismiss} />);
    UserEvent.click(screen.getByText("Open Dialog"));
    const document = getByRole("document");
    UserEvent.click(document.firstChild);
    expect(onDismiss).toHaveBeenCalled();

https://codesandbox.io/s/hungry-joliot-tjcph?file=/src/App.spec.js

diedu
  • 19,277
  • 4
  • 32
  • 49
  • Thanks for the explanation. Just curious did the test succeeded in the codesandbox url you posted? I ran your modified version of test in codesandbox directly but it still gave me the same result – Shi Cheng Jun 11 '21 at 15:32
  • @ShiCheng sorry I forgot I changed the App component code and saved it by accident, you can check again, now it is passing – diedu Jun 11 '21 at 15:49
  • I see it passing and why it's passing now. Thank you so much! – Shi Cheng Jun 11 '21 at 17:26