vitest-dev / vitest

Next generation testing framework powered by Vite.
https://vitest.dev
MIT License
13.15k stars 1.19k forks source link

Browser Mode - Add an API for accessing content rendered in iframes #6966

Open EdwardSalter opened 3 days ago

EdwardSalter commented 3 days ago

Clear and concise description of the problem

As a develoepr using Vitest browser mode, I want to be able to search for elements within an iframe that is rendered by tested code. If my code under test renders an iframe, I currently have no way of accessing elements within that iframe since the page object is scoped to the global iframe where the component under test is rendered and any iframe rendered within this will not have it's content visible to the page object.

Suggested solution

It would be good to have the ability to create a new BrowserPage from an iframe element:

const iframeContent = '<p>text in the iframe</p>';
const ReactComponentThatRendersIframe = () => {
  return ( <iframe data-testid="the=iframe" srcdoc={iframeContent} /> )
}

it('renders an iframe with the correct text', async () => {
  render(<ReactComponentThatRendersIframe />);

  const myFrameElement = page.getByTestId('the-iframe');
  await expect.element(myFrameElement).toBeInTheDocument();

  const myFramePage: BrowserPage = makeMyFrameABrowserPage(myFrameElement); // Magic here

  // Now `myFramgePage` can be used in the exact same manner as `page`
  const textInIframe = myFramePage.getByText('text in the iframe');
  await expect.element(textInIframe).toBeInTheDocument();
})

Alternative

The only way to get elements within the iframe at the minute would be to create a custom command and access the playwright APIs directly. There is no way of passing this element back to the test code however and the command would likely have to contain logic that should belong in the test.

Additional context

No response

Validations