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方法創(chuàng)建,輸入?yún)?shù)是正式的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里的元素:
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).
調(diào)用完query之后,如果不顯式調(diào)用fixture.detectChanges, 則query返回的handle里,是無法獲取到視圖內(nèi)容的。
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環(huán)境的wrapper,因此在單元測試代碼里,我們可以自行控制change detection的觸發(fā)時(shí)機(jī)。
it('login button hidden when the user is authenticated', () => {expect(el.nativeElement.textContent.trim()).toBe('');fixture.detectChanges();expect(el.nativeElement.textContent.trim()).toBe('Login'); }); 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Angular单元测试fixture.detectChanges()的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: yyyy-mm-dd是什么格式(日期格式
- 下一篇: 王者荣耀司马懿技能连招铭文