当在Angular中使用Jasmine使用* ngIf指令时,如何单元测试元素是否可见 [英] How do I unit test if an element is visible when the *ngIf directive is used using Jasmine in Angular
问题描述
我有一个Angular 6应用,并编写一些单元测试,试图仅根据*ngIf
指令的布尔结果来确定某个元素是否可见.
I have an Angular 6 app and writing some unit tests trying to determine if an element is visible or not based solely on the boolean result of an *ngIf
directive.
标记:
<div class="header" *ngIf="show">
<div>...</div>
</div>
规格文件:
it('should hide contents if show is false', () => {
const button = debugElement.query(By.css('button')).nativeElement;
button.click(); // this will change show to false
fixture.detectChanges();
expect(debugElement.query(By.css('.header')).nativeElement.style.hidden).toBe(true);
});
我似乎无法从div获得hidden
属性. angular是否使用*ngIf
指令使用另一种方法从DOM中隐藏元素?我需要从nativeElement
获取另一个属性吗?
I can't seem to get the hidden
attribute from the div. Does angular use another approach to hiding the element from the DOM using the *ngIf
directive? Do I need to get another property from the nativeElement
?
谢谢!
推荐答案
如果该元素是隐藏的,则不会在dom内部呈现.
If the element is hidden, then it wont be rendered inside the dom.
您可以检查
expect(fixture.debugElement.query(By.css('.header'))).toBeUndefined();
编辑:toBeNull()
在上述情况下效果更好
EDIT : toBeNull()
works better in the above case
expect(fixture.debugElement.query(By.css('.header'))).toBeNull();
在获取按钮元素时,还会出现语法错误. nativeElement
不是函数.
And also you have a syntax error while fetching the button element. nativeElement
is not a function.
以这种方式更改它:
const button = fixture.debugElement.query(By.css('button')).nativeElement;
这篇关于当在Angular中使用Jasmine使用* ngIf指令时,如何单元测试元素是否可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!