我想测试按钮的功能,但是该元素在页面上不可见,因为它位于*ngIf
下。我想将*ngIf
中的变量设置为true,以便能够显示数据。我尝试用:
beforeEach(() => {
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
component.currentUser = {firstName: 'xxx'} as User; // Changing currentUser so it won't be undefined anymore
fixture.detectChanges();
});
但仍然无法正常工作。这是我的组件:
<div class="menu-button-container">
<div class="menu-button" [ngClass]="{'menu-open': isMenuOpen}" (click)="toggleMenu()" *ngIf="currentUser">
<div class="line-menu-button line-menu-button__top"></div>
<div class="line-menu-button line-menu-button__middle"></div>
<div class="line-menu-button line-menu-button__bottom"></div>
</div>
</div>
和我尝试运行的测试:
it('should open the menu when the button menu is clicked', () => {
const fixture = TestBed.createComponent(HeaderComponent);
fixture.detectChanges();
const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
expect(menuDebugElement).toBeTruthy();
});
这总是失败。如果我将*ngIf
规则定义为*ngIf="currentUser"
,则测试正在运行。如何从测试中更改此变量?请指教!谢谢!
更改currentUser变量的值:
it('should open the menu when the button menu is clicked', () => {
const fixture = TestBed.createComponent(HeaderComponent);
const component = fixture.componentInstance;
component.currentUser = true;
fixture.detectChanges();
const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
expect(menuDebugElement).toBeTruthy();
});