material-components / material-components-web

Modular and customizable Material Design UI components for the web
https://material.io/develop/web
MIT License
17.15k stars 2.15k forks source link

[MDCBanner] Getting error` FocusTrap: Element must have at least one focusable child. ` only during test #7120

Open NikkiTheBugSlayer opened 3 years ago

NikkiTheBugSlayer commented 3 years ago

Bug report

After upgrading to v11 I am getting the FocusTrap: Element must have at least one focusable child. error only during testing using jest and React testing library when I when I try to test the opened event. I have ensured that there are focusable elements, but I am still getting the error. Is there a work around for this?

Actual behavior

Tests fail when testing opened event due to above focus trap error

Expected behavior

Tests not fail

Screenshots

image

joshuabremerdexcom commented 2 years ago

I'm getting this too. I believe this is due to this code: https://github.com/material-components/material-components-web/blob/master/packages/mdc-dom/focus-trap.ts#L135-L136=

        isProgrammaticallyHidden =
            style.display === 'none' || style.visibility === 'hidden';

When I run tests using ember.js, the test container that holds the elements is hidden, therefore the elements are hidden. I need to find a way to update the test to skip the focus or think the images are visible.

joshuabremerdexcom commented 2 years ago

If someone has a more idiomatic way, I'd love to hear. My solution for now is to add this style to our component:

  #ember-testing-container & {
    [autofocus],
    [tabindex],
    a,
    input,
    textarea,
    select,
    button {
      visibility: visible !important;
    }
  }

The idea here is that if any of these elements are rendered inside the #ember-testing-container, they will be visible, allowing the library to find them. It's pretty hacky, It causes some flashing buttons in the tests, but ensures that any consumer who uses it can write tests, which I think is worth the tradeoff.