gau*_*430 6 reactjs react-testing-library testing-library
在React测试库中,按照惯例,最好使用屏幕而不是从渲染中解构方法。
我有一个组件,我需要在其中测试渲染的文本。该组件中的顶级容器是 div,因此没有可访问的查询来获取文本匹配。如何使用屏幕进行文本匹配?
我目前已经求助于使用解构道具中的容器,然后在容器上进行文本匹配。
// MyComponent - simplified
const MyComponent = () => <div> some text </div>
// test
const { container } = render(<MyComponent />);
expect(container).toHaveTextContent(...)
Run Code Online (Sandbox Code Playgroud)
参考: https: //kentcdodds.com/blog/common-mistakes-with-react-testing-library#not-using-screen
在博客文章中提到,解构主要是为了遗留目的而支持的,但没有任何用例不能使用屏幕来解决。这个用例可以使用屏幕来解决吗?
小智 2
您应该将项目包装在其指定的角色中(可以在此处找到)。
div未定义为角色,因此您可以将其更改为
h1使其具有语义并且更易于测试。这是它的样子
function App(){
return <h1>Some random text</h1>
}
// Test
describe("App component", () => {
it("renders heading", () => {
render(<App />);
expect(screen.getByRole('heading',{level:1})).toBeInTheDocument()
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7659 次 |
| 最近记录: |