Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test HTML content with React testing library

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

like image 465
Frontend employee Avatar asked Jun 02 '20 11:06

Frontend employee


People also ask

Do you need Jest for React testing library?

However, there are some things you can do when configuring your testing framework to reduce some boilerplate. In these docs we'll demonstrate configuring Jest, but you should be able to do similar things with any testing framework (React Testing Library does not require that you use Jest).

How do I test my code on React?

You can run the test using the command – npm run test. The output will show the test results as shown in the figure.


1 Answers

You're using "@testing-library/jest-dom/extend-expect" which provides a set of custom jest matchers that you can use, fore example you have toHaveTextContent(text: string | RegExp, options?: {normalizeWhitespace: boolean}) that you can use here:

const checkContent = screen.getByTestId("title-content");
expect(checkContent).toHaveTextContent("Dashboard Menu");
like image 150
Fraction Avatar answered Sep 23 '22 19:09

Fraction