TestingLibraryElementError: Unable to find an accessible element with the role "blah" Here are the accessible roles: button: Name "Hello World": --- Hello World 这里要注意的是,我们并没有为 设置Role 而加上 role=button。因为这是隐式的 Role,下一节会详细说明。 建议:阅读...
// ❌const{getByRole}=render(<Example/>)consterrorMessageNode=getByRole('alert')// ✅render(<Example/>)consterrorMessageNode=screen.getByRole('alert') screen是在 DOM Testing Library v6.11.0 引入的 (就就是说,你可以在@testing-library/react@>=9这些版本中使用它)。直接在render引入的时候...
import {render, screen} from '@testing-library/react' 1. 使用screen 的好处是:在添加/删除 DOM Query 时,不需要实时地解构 render 的返回值来获取内容。输入 screen,你的编辑器就能自动补全它里面的 API 了。 除非一种情况:你在配置 container 或者 baseElement。不过,你应该避免使用它们(因为我实在想不出...
// ❌const {getByRole} = render(<Example />)const errorMessageNode = getByRole('alert')// ✅render(<Example />)const errorMessageNode = screen.getByRole('alert') screen是在 DOM Testing Library v6.11.0 引入的(就就是说,你可以在@testing-library/react@>=9这些版本中使用它)。直接在r...
element) { throw new Error( `Unable to fire a "${event.type}" event - please provide a DOM element.`, ) } return element.dispatchEvent(event) }) } 那我们看看 React Testing Library 中又做了啥,它其实是对 fireEvent 加了层 act 包裹,这也是我们能直接使用的原因, fireEvent 时切记不要再...
testing-library 的核心部分是DOM Testing Library即@testing-library/dom, 它提供了通用的DOM 查询功能,如getByRolegetByText与事件行为的基本实现。 在此基础上,再衍生出各自框架的专有包,如React Testing Library、Vue Testing Library,对于不同的前端框架,其使用方法是基本一致的, 提供不同实现方式的render与fireE...
console, 'error').mockImplementation((...args) => { // This function will be called whenever a test fails if (typeof args[0] === 'string' && args[0].includes('TestingLibraryElementError')) { // Print the state of the DOM when a TestingLibraryElementError occurs screen.debug(); ...
在现代的React中,Jest是最热门的JavaScript程序的测试框架,我们不可避免要去接触。如果是通过 create-react-app 来创建项目,则 Jest 及 React Testing Library 已经默认安装了,在package.json可以看到test script,我们可以通过npm test来运行测试。在此之前,我们先看下面的测试代码: ...
import { render, screen } from '@testing-library/react';import App from './App'; test('renders learn react link', () => { render(<App />); const linkElement = screen.getByText(/learn react/i); expect(linkElement).toBeInTheDocument(); ...
那个时候,觉得测试就是写 test case,写断言,跑测试,以及查看 test case 的 coverage。整个流程和写法也不是特别难,所以就理所当然地觉得,写测试也不是特别难。 加上之前实际的工作中,也没有太多的写测试的经历,所以当自己需要对组件库补充单元测试的时候,发现并不能照葫芦画瓢来写单测。一时不知道该...