SAP Spartacus的Lock Focus Directive单元测试实现
測試用的HTML頁面:
<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實現里,選取每一組的部分子元素,注入到service.findFocusable的返回結果集里。
第一組測試:id為a的a標簽,tabindex應該被設置為0:
lockFocus directive的默認配置:
注意shouldLock的標志位是通過config.lock決定的:
b標簽通過顯式傳入的lock:true,也將tabindex設置為0,這一點同a標簽一樣:
c標簽:如果顯式地傳入lock:false:
則host元素的tabindex不發生變化,仍然是初始值5:
在configuration測試里,監控event對象的stopPropagation方法,并且讓service的hasFocusableChildren方法返回false.
describe('configuration', () => {beforeEach(() => {spyOn(event, 'stopPropagation');spyOn(service, 'hasFocusableChildren').and.returnValue(false);fixture.detectChanges();});顯式觸發a標簽的回車事件:
注意上圖代碼,在使用代碼觸發a標簽的keydown.enter事件時,也要將mock過后的event對象傳到event handler里去。
根據lockFocus directive的實現,在handleEnter方法里會調用event.stopPropagation:
如果lock=false,則enter事件觸發后,不應該自動被unlock, 單元測試代碼:
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,因此無法進入下圖的IF分支。
子元素的鎖定測試:
b1,b2, b3應該全部被鎖住,tabindex為-1:
為什么要tick(500)?
只要lock=true,就會自動將autofocus設置為true:
在view渲染完畢之后,會調用handleFocus:
handleFocus里會調用setTimeout執行lockFocus方法:
b4,b5屬于non-focusable標簽,不應該被lock:
b4沒有href屬性,b5是p標簽,都不應被鎖住。
如果lock=false,也不應被lock,tabindex不應該為-1:
如果child具有persisted focus,那么不應再lock:
d1和d2的定義:
enter事件觸發時,執行unlockFocus方法:
unlockFocus會將子元素的tabindex設置成0:
persist group的測試:
b1,b2,b3會自動被添加上data-cx-focus-group的屬性,值為config里傳入的g1:
b4, b5不是focusable element,所以不應該被設置data-cx-focus-group屬性。
id為a的a標簽會在escape時觸發service的handleEscape方法:
如果lock=false,那么escape時沒必要unlock:
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的SAP Spartacus的Lock Focus Directive单元测试实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为p30夜景怎么拍
- 下一篇: fixture.detectChange