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");
});
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).
You can run the test using the command – npm run test. The output will show the test results as shown in the figure.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With