testing-library / dom-testing-library

🐙 Simple and complete DOM testing utilities that encourage good testing practices.
https://testing-library.com/dom
MIT License
3.26k stars 467 forks source link

Unexpected spaces around inline DOM elements in accessibility names #1164

Closed nstepien closed 2 years ago

nstepien commented 2 years ago

Relevant code or config:

import { render, screen } from '@testing-library/react';

test('my test', () => {
  render(
    <div role="option">
      t<mark>e</mark>st
    </div>
  );

  screen.getByRole('option', { name: 'test' });
});

What you did:

I'm trying to match elements by their role and name. We render a list of options, and depending on the text input the user may have entered, we mark matching text nodes.

What happened:

  ● my test                                                                                                       

    TestingLibraryElementError: Unable to find an accessible element with the role "option" and name "test"       

    Here are the accessible roles:

      option:

      Name "t e st":
      <div
        role="option"
      />

      --------------------------------------------------

    Ignored nodes: comments, script, style
    <body>
      <div>
        <div
          role="option"
        >
          t
          <mark>
            e
          </mark>
          st
        </div>
      </div>
    </body>

       8 |   );
       9 |
    > 10 |   screen.getByRole('option', { name: 'test' });
         |          ^
      11 | });
      12 |

      at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:40:19)
      at node_modules/@testing-library/dom/dist/query-helpers.js:90:38
      at node_modules/@testing-library/dom/dist/query-helpers.js:62:17
      at node_modules/@testing-library/dom/dist/query-helpers.js:111:19
      at Object.getByRole (src/components/Autocompleter/my.test.tsx:10:10)

Reproduction:

See code above, or https://codesandbox.io/s/react-testing-library-demo-forked-mc560z?file=/src/__tests__/hello.js

Problem description:

I'd expect inline elements, such as <mark> or <span> not to introduce spaces around them in accessibility names.

Suggested solution:

Maybe inline rendering can be assume for some DOM nodes?

eps1lon commented 2 years ago

This is likely a bug in JSDOM. We do consider display for the whitespace. Only block elements are joined by a space. If I try it in a browser, it returns 'test' as expected: https://codesandbox.io/s/zen-cartwright-ql4org?file=/src/index.js.

Seems like mark is considered a block element in JSDOM. There's a default stylesheet in JSDOM. Maybe it's as simple as adding mark { display: inline; } to that.