天天看點

Angular單元測試fixture.detectChanges()

https://codecraft.tv/courses/angular/unit-testing/change-detection/

ATB:Angular Test Bed

// create component and test fixture

fixture = TestBed.createComponent(LoginComponent);

fixture通過ATB的createComponent方法建立,輸入參數是正式的Component.

The fixture as well as holding an instance of the component also holds a reference to something called a DebugElement, this is a wrapper to the low-level DOM element that represents the component’s view, via the debugElement property.

通過fixture.debugElement擷取Component view裡的元素:

Angular單元測試fixture.detectChanges()

We can get references to other child nodes by querying this debugElement with a By class. The By class lets us query using a number of methods, one is via a CSS class like we have in our example, another way is to request by a type of directive like By.directive(MyDirective).

調用完query之後,如果不顯式調用fixture.detectChanges, 則query傳回的handle裡,是無法擷取到視圖内容的。

That’s because when Angular first loads no change detection has been triggered and therefore the view doesn’t show either the Login or Logout text.

fixture is a wrapper for our component’s environment so we can control things like change detection.

fixture是Component環境的wrapper,是以在單元測試代碼裡,我們可以自行控制change detection的觸發時機。

it('login button hidden when the user is authenticated', () => {

 expect(el.nativeElement.textContent.trim()).toBe('');

 fixture.detectChanges();

 expect(el.nativeElement.textContent.trim()).toBe('Login');

});

繼續閱讀