You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// App 组件functionApp(){return(<form><labelhtmlFor="title-input">Title</label><inputid="title-input"/><labelhtmlFor="content-input">Content</label><textareaid="content-input"/><labelhtmlFor="tags-input">Tags</label><inputid="tags-input"/><buttontype="submit">Submit</button></form>)}// App.test.js 测试组件import{render,screen}from"@testing-ibrary/react"test('renders a form with title, content, tags, and a submit button',()=>{render(<Editor/>)screen.getByLabelText(/title/i)screen.getByLabelText(/content/i)screen.getByLabelText(/tags/i)screen.getByText(/submit/i)})
二、触发事件
使用 userEvent 来触发事件,比如下面的点击
// Editor.js functionEditor(){functionhandleSubmit(e){e.preventDefault()setIsSaving(true)}return(<formonSubmit={handleSubmit}><labelhtmlFor="title-input">Title</label><inputid="title-input"/><buttontype="submit"disabled={isSaving}>
Submit
</button></form>)}// Editor.test.jstest('renders a form with title, content, tags, and a submit button',()=>{render(<Editor/>)constsubmitButton=screen.getByText(/submit/i)userEvent.click(submitButton)expect(submitButton).toBeDisabled()})
三、测试 hook 组件
有两个比较关键的 api render 和 act render 是渲染组件,调用 act 是进行对组件的更新
varevent=newEvent('build');// Listen for the event.elem.addEventListener('build',function(e){ ... },false);// Dispatch the event.elem.dispatchEvent(event);
RTL 测试
一、获取 dom
查找 Dom 元素使用
getxxx
、queryxxx
、findxxxx
这三种查找方式通过在其后缀 All 之后就会查找多个元素,如果没有使用在后缀All的这种形式,查找元素存在多个的条件下就会抛出错误
二、触发事件
使用
userEvent
来触发事件,比如下面的点击三、测试 hook 组件
有两个比较关键的 api
render
和act
render
是渲染组件,调用act
是进行对组件的更新事件
在 RTL 中有两种事件测试的包
userEvent
和fireEvent
userEvent
可以完整的模仿一套事件的触发,而fireEvent
是直接触发了事件,使用dispatchEvnet
方法。这就会导致在一前者的文件提交较大,后者更轻量化,在一些简单的事件操作下使用fireEvent
就行。使用到
userEvent
事件去触发常见的有以下几种
使用
type
方法在input
或textarea
去写入这块东西有些多,没总结过来,具体的事件看官网吧...
Jest 测试框架
全局钩子
affterAll
:大意就是在当前文件下运行完所有的测试结果后会掉用你通过affterAll
传入的 函数 ,如果返回值是promise
则会等待它处理完。affterEach
在每个测试文件完成之后调用一次传入的函数,如果返回的是promise
orgenerator
会等待它处理完beforeAll
在运行此文件中的任何测试之前运行函数,如果返回的是promise
orgenerator
会等待它处理完beforeEach
在运行此文件中的每个测试之前运行一个函数, 在运行此文件中的每个测试之前运行一个函数前面四种函数可以接收两个参数 (
fn
,timeout
), 回调函数 fn 和 超时时间 默认为 5s 超过 5s 就会结束模拟函数
关于模拟函数参考这篇文章:#66
清除
在一些不支持使用
afterEach
这样自动注入到测试环境下的话需要自己去手动清除,但 jest、mocha 都会自动的去清除使用定时器需要注意的事项
在使用定时器时,在一些其它测试框架一般会采取虚拟定时器来模仿,为了确保在测试后不会改变原定时器功能尽量在测试后去恢复
在测试中所有的定时器都使用
虚拟定时器
。在测试结束后运行所有挂起的定时器并将
虚拟定时器
还原成定时器
The text was updated successfully, but these errors were encountered: