首页 > 解决方案 > 如何使用 React 测试库测试 HTML 内容

问题描述

目前我正在编写一个测试来测试里面的内容(HTML 内容),但似乎我无法使用 React 测试库正确地测试它。它可以找到它的 id 值,但是我如何获取该元素内的 HTML 内容。

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");
});

在此处输入图像描述

标签: javascripthtmlreactjsreact-testing-library

解决方案


您正在使用"@testing-library/jest-dom/extend-expect"它提供了一组您可以使用的自定义笑话匹配器,例如您toHaveTextContent(text: string | RegExp, options?: {normalizeWhitespace: boolean})可以在此处使用:

const checkContent = screen.getByTestId("title-content");
expect(checkContent).toHaveTextContent("Dashboard Menu");

推荐阅读