Angular jasmine fixture.detectChanges如何触发directive的set方法
生活随笔
收集整理的這篇文章主要介紹了
Angular jasmine fixture.detectChanges如何触发directive的set方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
測試代碼:
import { Component } from '@angular/core'; import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { FocusDirective } from './focus.directive'; import { KeyboardFocusService } from './services'; import { By } from '@angular/platform-browser';@Component({selector: 'cx-host',template: ` <div id="b" [cxFocus]="{autofocus: ':host'}" [cxRefreshFocusOn]="jerry"></div> `, }) class MockComponent {jerry = 1; }class MockKeyboardFocusService {get() {}set() {}shouldFocus() {}getPersistenceGroup() {}findFirstFocusable(){}hasPersistedFocus(){} }describe('FocusDirective', () => {let fixture: ComponentFixture<MockComponent>;let component: MockComponent;beforeEach(waitForAsync(() => {TestBed.configureTestingModule({declarations: [FocusDirective, MockComponent],providers: [{provide: KeyboardFocusService,useClass: MockKeyboardFocusService,},],}).compileComponents();fixture = TestBed.createComponent(MockComponent);component = fixture.componentInstance;fixture.detectChanges();}));it('should focus itself', () => {let service: KeyboardFocusService;service = TestBed.inject(KeyboardFocusService);const host = fixture.debugElement.query(By.css('#b'));const el = host.nativeElement;spyOn(service, 'findFirstFocusable').and.returnValue(el);spyOn(el, 'focus').and.callThrough();fixture.detectChanges();const event = {preventDefault: () => {},stopPropagation: () => {},};host.triggerEventHandler('focus', event);expect(el.focus).toHaveBeenCalled();expect(service.findFirstFocusable).toHaveBeenCalled();component.jerry = 2;fixture.detectChanges();}); });在單元測試代碼里顯式修改Component的jerry屬性為2:
detectChanges會觸發ngZone的run方法,進而調用_tick函數:
以callback的方式回調_tick():
changeDetectorRef指向RootViewRef, 因此執行Root view的change detection策略:
最后執行到refreshView里的executeTemplate方法:
執行template function:
待更新template的屬性名稱:cxRefreshFocusOn, 屬性值:2
function elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, nativeOnly) {ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');const element = getNativeByTNode(tNode, lView);let inputData = tNode.inputs;let dataValue;if (!nativeOnly && inputData != null && (dataValue = inputData[propName])) {setInputsForProperty(tView, lView, dataValue, propName, value);if (isComponentHost(tNode))markDirtyIfOnPush(lView, tNode.index);if (ngDevMode) {setNgReflectProperties(lView, element, tNode.type, dataValue, value);}}這個33是element在LView中的索引值:
從lView里根據索引值33拿到directive實例:
最后設置該實例的值為2:
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的Angular jasmine fixture.detectChanges如何触发directive的set方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Flash CS6如何制作水墨梅花的生长
- 下一篇: 什么叫出票人,普票的含义