javascript - 如何使用 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");
});
解决方案
您正在使用"@testing-library/jest-dom/extend-expect"
它提供了一组您可以使用的自定义笑话匹配器,例如您toHaveTextContent(text: string | RegExp, options?: {normalizeWhitespace: boolean})
可以在此处使用:
const checkContent = screen.getByTestId("title-content");
expect(checkContent).toHaveTextContent("Dashboard Menu");
推荐阅读
- c# - C# .NET 4.6 等效于 Unsafe.As
- uml - 如何在 Uml 用例图中显示工具栏
- r - 将数字向量切割成箱
- c# - Visual Studio 16.8 打破 .NET Framework 4.8 WPF 构建
- react-native - react-native Text 输入溢出文本
- sql - Postgres 普通查询中的逻辑
- povray - 基于字符串长度的条件
- ruby-on-rails - 将不同的查询与 Active Record/Arel 结合
- python - 当类属性为私有时返回对象的字典表示(Python)
- python - 在 matplotlib 中为子图赋予标题