javascript 如何使用React测试库测试HTML内容

rn0zuynd  于 2023-04-10  发布在  Java
关注(0)|答案(5)|浏览(94)

目前我正在写一个测试来测试里面的内容(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");
});

j8yoct9x

j8yoct9x1#

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

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

jgzswidk2#

也可以通过这种方式测试整个HTML节点结构:

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

这是使用标准web API Element.outerHTML

oxalkeyp

oxalkeyp3#

使用getByText

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

vqlkdk9b4#

你可以使用within来获取文本Dashboard Menu。试试这个:

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()
});
mitkmikd

mitkmikd5#

如果你需要访问HTML元素本身的类型,除了内容,你可能需要使用getByText方法和回调函数。

test("It should check if content matches", () => {
  render(<App />);

  const checkContent = screen.getByText((content, element) => {
      return element.tag.toLowerCase() === 'div' &&  content.includes('Dashboard Menu')
  });

    expect(checkContent).toBeInTheDocument();
});

相关问题