700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Angular单元测试fixture.detectChanges()

Angular单元测试fixture.detectChanges()

时间:2022-11-03 22:50:05

相关推荐

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里的元素:

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');});

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。