問題描述
我有一個 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();
EDIT : 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 指令時,如何對元素是否可見進行單元測試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!