how to get the rendered HTML element from the screen, from react testing library?
Asked Answered
V

1

8

IN the react testing library, I want to get the entire rendered HTML, from the screen and check if this rendered correctly and is present in the dom.

I see that the screen has the methods to query the DOM, but how to access full HTML which is rendered.

import React from 'react';
import {render, screen} from '@testing-library/react';
import '@testing-library/jest-dom';
import {server} from '../__mock__/server.mock';
import InfoBar from '../Components/infoBar';

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('InfoBar renders correctly.', async () => {
    render(<InfoBar/>);
    expect(screen).toBeInTheDocument();
});

expect(screen).toBeInTheDocument(); this doesnt work.

Vaccaro answered 18/2, 2022 at 13:4 Comment(0)
A
6

If you want to get entire HTML, you can try using

const { container } = render(<InfoBar />);
expect(container).toMatchSnapshot()

This will save a snapshot file, which you can review.

Or to get the snapshot of HTML there and there itself, you can use:

expect(container).toMatchInlineSnapshot()

and then run test, which will then fill brackets of toMatchInlineSnapshot() with the HTML like so:

expect(container).toMatchInlineSnapshot(`
  <div>
    <p>Hello World</p>
  </div>
`)

For more, refer here: Snapshot Testing

Arachne answered 18/2, 2022 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.