Reactjs 反应测试库:匹配按钮数

Reactjs 反应测试库:匹配按钮数,reactjs,react-testing-library,Reactjs,React Testing Library,我已使用create react app创建了一个应用程序。下面是我的计数器组件和测试文件。我正在尝试为组件中的三个静态按钮创建一个测试。第一个测试运行良好,而第二个测试给出了下面提供的错误 反应组分: 从“React”导入React; 从“道具类型”导入道具类型; 从“/Counter.module.css”导入类; 功能计数器(道具){ 返回( 单击计数器-{props.value} 增量 {/*减量 重置*/} ); } Counter.propTypes={ 值:PropTypes.

我已使用create react app创建了一个应用程序。下面是我的计数器组件和测试文件。我正在尝试为组件中的三个静态按钮创建一个测试。第一个测试运行良好,而第二个测试给出了下面提供的错误

反应组分:

从“React”导入React;
从“道具类型”导入道具类型;
从“/Counter.module.css”导入类;
功能计数器(道具){
返回(

单击计数器-{props.value}

增量 {/*减量 重置*/} ); } Counter.propTypes={ 值:PropTypes.number, clickHandler:PropTypes.func, }; 导出默认计数器;
测试文件:

从“React”导入React
从'@testing library/react'导入{render,firevent,screen,cleanup}
从“/Counter”导入计数器;
每次之后(清理);
描述('计数器',()=>{
测试('呈现计数器值10',()=>{
render();
//screen.debug();
期望(screen.getByText(/单击计数器-/).toBeInTheDocument();
})
})
测试('呈现三个按钮',()=>{
render();
const items=screen.findAllByRole(“按钮”);
期望(项目)。有长度(3);
})
错误消息:

失败src/components/Counter/Counter.test.js ● 渲染三个按钮 expect(已接收)。toHaveLength(预期) 匹配器错误:收到的值必须具有值必须为数字的length属性 接收到的类型为:对象 接收到的值:{} 19 | render(); 20 | const items=screen.findAllByRole(“按钮”); >21 |预计(项目)。有长度(3); | ^ 22 | }) at Object..test(src/components/Counter/Counter.test.js:21:19)*


在提供的示例中,您使用的是
.findAllByRole('button')
,它返回一个承诺,需要等待,如下所示:

test('renders three button',async()=>{
render()
常量项目=等待屏幕。findAllByRole('按钮')
expect(项目)。toHaveLength(3)

})
第一个给出此错误:TypeError:MutationObserver不是构造函数20 | test('renders three button',async()=>{21 | render()>22 | const items=wait screen.findAllByRole('button')^23 | expect(items).toHaveLength(3)24})然而,第二个像一个魅力!感谢CreateReact应用程序的jest/jsdom版本中出现了MutationObserver错误。更多信息和潜在的解决方案在这里