Skip to content

Cannot query children in <Portal>s #62

Open
@gBasil

Description

@gBasil

The query commands (getByRole, getByTestId, etc.) fail to pick up children of <Portal>s.


The children of <Portal>s get rendered in a separate <div> from the content of the render call. The various query commands seem to use the container element, which is the first <div>, and fail to pick up anything in a portal:

import { expect, test } from 'vitest';
import { render } from '@solidjs/testing-library';
import { Portal } from 'solid-js/web';

test('Portal test', () => {
  const { getByTestId, debug } = render(() => <>
    <p data-testid='one'>One</p>
    <Portal>
      <p data-testid='two'>Two</p>
    </Portal>
  </>);

  getByTestId('one'); // Succeeds
  getByTestId('two'); // Throws an error

  debug(); // Prints the following:
  /*
    <body>
      <div>
        <p data-testid="one">
          One
        </p>

      </div>
      <div>
        <p data-testid="two">
          Two
        </p>
      </div>
    </body>
  */
});

One workaround is to use the baseElement property with a query selector, i.e. baseElement.querySelector('[data-testid="two"]'). However, Solid Testing Library reuses the <body> between render()s:

test('aaa', () => {
  render(() => <p>test 1</p>);
  render(() => <p>test 2</p>);
  const res = render(() => <p>test 3</p>);

  res.debug(); // Prints out the following:
  /*
    <body>
      <div>
        <p>test 1</p>
      </div>
      <div>
        <p>test 2</p>
      </div>
      <div>
        <p>test 3</p>
      </div>
    </body>
  */
});

So, if you have two tests in one file, they will both be rendered in the same document, and so you'll likely run into issues when using baseElement.querySelector, as it might select elements from a different test.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions