How to test HTML content with React testing library

Viewed 19349

Currently I am writing a test to test the content that is inside (HTML content), but it seems I cannot test that properly with React testing library. It can find the id value of that, but how do I get the HTML content inside that element.

import React from 'react';

export const TopBar = () => {
    return (
        <div className="dashboard-title-component">
            <div>
                <div data-testid="title-content">Dashboard Menu</div>
            </div>
        </div>
    )
}

import React from "react";
import { render } from "@testing-library/react";
import { TopBar } from "./TopBar";
import { Provider } from "react-redux";
import { store } from "../../Store";
import { screen } from "@testing-library/dom";
import "@testing-library/jest-dom/extend-expect";

test("It should check if content matches", () => {
    render(
        <Provider store={store}>
            <TopBar/>
        </Provider>
    )
    const checkContent = screen.getAllByTestId("title-content");
    expect(checkContent.text()).toBe("Dashboard Menu");
});

enter image description here

4 Answers

It is possible to also test whole HTML node structure this way:

const checkContent = screen.getByTestId("title-content");
expect(checkContent.outerHTML)
    .toEqual("<div data-testid=\"title-content\">Dashboard Menu</div>");

This is using standard web API Element.outerHTML

You can use within to get the text Dashboard Menu. Try this:

test("It should check if content matches", () => {
    const { getByTestId } = render(
        <Provider store={store}>
            <TopBar/>
        </Provider>
    )
    const { getByText } = within(getByTestId('title-content'))
    expect(getByText('Dashboard Menu')).toBeInTheDocument()
});

Use getByText

test("It should check if content matches", () => {
  const { getByText } = render(<Provider store={store}><TopBar /></Provider>)
  expect(getByText(/dashboard menu/i)).toBeTruthy();
});
Related