SAP Spartacus的Lock Focus Directive单元测试实现
測(cè)試用的HTML頁(yè)面:
<div cxLockFocus id="a"><button id="a1"></button><a href="" id="a2"></a></div><div [cxLockFocus]="{ lock: true, group: 'g1' }" id="b" tabindex="-1"><button id="b1"></button><a href="" id="b2"></a><textarea id="b3"></textarea><a id="b4"></a><p id="b5"></p></div><div [cxLockFocus]="{ lock: false }" id="c" tabindex="5"><button id="c1"></button><a href="" id="c2"></a></div><div[cxLockFocus]="{ lock: true, focusOnEscape: false, autofocus: false }"id="d"><button id="d1"></button><a href="" id="d2" data-cx-focus="d2"></a></div><div [cxLockFocus]="{ lock: true, autofocus: 'button' }" id="e"><a href="" id="e1"></a><button id="e2"></button><button id="e3"></button></div>
這些方法可以全部mock:
在beforeEach實(shí)現(xiàn)里,選取每一組的部分子元素,注入到service.findFocusable的返回結(jié)果集里。
第一組測(cè)試:id為a的a標(biāo)簽,tabindex應(yīng)該被設(shè)置為0:
lockFocus directive的默認(rèn)配置:
注意shouldLock的標(biāo)志位是通過(guò)config.lock決定的:
b標(biāo)簽通過(guò)顯式傳入的lock:true,也將tabindex設(shè)置為0,這一點(diǎn)同a標(biāo)簽一樣:
c標(biāo)簽:如果顯式地傳入lock:false:
則host元素的tabindex不發(fā)生變化,仍然是初始值5:
在configuration測(cè)試?yán)?#xff0c;監(jiān)控event對(duì)象的stopPropagation方法,并且讓service的hasFocusableChildren方法返回false.
describe('configuration', () => {beforeEach(() => {spyOn(event, 'stopPropagation');spyOn(service, 'hasFocusableChildren').and.returnValue(false);fixture.detectChanges();});顯式觸發(fā)a標(biāo)簽的回車事件:
注意上圖代碼,在使用代碼觸發(fā)a標(biāo)簽的keydown.enter事件時(shí),也要將mock過(guò)后的event對(duì)象傳到event handler里去。
根據(jù)lockFocus directive的實(shí)現(xiàn),在handleEnter方法里會(huì)調(diào)用event.stopPropagation:
如果lock=false,則enter事件觸發(fā)后,不應(yīng)該自動(dòng)被unlock, 單元測(cè)試代碼:
it('should not unlock when lock=false', () => {const host = fixture.debugElement.query(By.css('#c'));event.target = host.nativeElement;host.triggerEventHandler('keydown.enter', event);expect(event.stopPropagation).not.toHaveBeenCalled();});原因在于,如果lock=false,shouldLock也為false,因此無(wú)法進(jìn)入下圖的IF分支。
子元素的鎖定測(cè)試:
b1,b2, b3應(yīng)該全部被鎖住,tabindex為-1:
為什么要tick(500)?
只要lock=true,就會(huì)自動(dòng)將autofocus設(shè)置為true:
在view渲染完畢之后,會(huì)調(diào)用handleFocus:
handleFocus里會(huì)調(diào)用setTimeout執(zhí)行l(wèi)ockFocus方法:
b4,b5屬于non-focusable標(biāo)簽,不應(yīng)該被lock:
b4沒(méi)有href屬性,b5是p標(biāo)簽,都不應(yīng)被鎖住。
如果lock=false,也不應(yīng)被lock,tabindex不應(yīng)該為-1:
如果child具有persisted focus,那么不應(yīng)再lock:
d1和d2的定義:
enter事件觸發(fā)時(shí),執(zhí)行unlockFocus方法:
unlockFocus會(huì)將子元素的tabindex設(shè)置成0:
persist group的測(cè)試:
b1,b2,b3會(huì)自動(dòng)被添加上data-cx-focus-group的屬性,值為config里傳入的g1:
b4, b5不是focusable element,所以不應(yīng)該被設(shè)置data-cx-focus-group屬性。
id為a的a標(biāo)簽會(huì)在escape時(shí)觸發(fā)service的handleEscape方法:
如果lock=false,那么escape時(shí)沒(méi)必要unlock:
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的SAP Spartacus的Lock Focus Directive单元测试实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 华为p30夜景怎么拍
- 下一篇: 每个施加在HTML元素上的Angular