目前我正在写一个测试来测试里面的内容(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");
});
5条答案
按热度按时间j8yoct9x1#
你正在使用
"@testing-library/jest-dom/extend-expect"
,它提供了一组你可以使用的自定义jest匹配器,例如你可以在这里使用toHaveTextContent(text: string | RegExp, options?: {normalizeWhitespace: boolean})
:jgzswidk2#
也可以通过这种方式测试整个HTML节点结构:
这是使用标准web API Element.outerHTML
oxalkeyp3#
使用getByText
vqlkdk9b4#
你可以使用within来获取文本
Dashboard Menu
。试试这个:mitkmikd5#
如果你需要访问HTML元素本身的类型,除了内容,你可能需要使用
getByText
方法和回调函数。