react 单测 TestingLibraryElementError Unable to find an element with the text Hello World This could be because the text is broken up by multiple elements In this case you can provide a function for y
要解决TestingLibraryElementError错误,你可以提供一个函数来更灵活地匹配文本。
首先,你需要使用screen.getByText方法来获取包含"Hello World"文本的元素。然后,你可以通过提供一个函数作为第二个参数来自定义匹配逻辑。
以下是一个示例,展示了如何使用正则表达式来匹配文本:
import { render, screen } from '@testing-library/react';
test('should find element with text "Hello World"', () => {
render(<YourComponent />);
const element = screen.getByText(/Hello World/);
expect(element).toBeInTheDocument();
});
上述代码中,getByText方法使用了正则表达式/Hello World/作为文本匹配器,它将尝试匹配任何包含"Hello World"文本的元素。
你也可以使用其他的匹配逻辑,比如自定义函数、CSS选择器等,来更灵活地匹配文本。具体的匹配逻辑取决于你的具体需求
原文地址: https://www.cveoy.top/t/topic/hLD3 著作权归作者所有。请勿转载和采集!