角度单元测试-在测试中更改组件变量

问题描述 投票:0回答:1

我想测试按钮的功能,但是该元素在页面上不可见,因为它位于*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",则测试正在运行。如何从测试中更改此变量?请指教!谢谢!

angular unit-testing karma-jasmine
1个回答
0
投票

更改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();
});
© www.soinside.com 2019 - 2024. All rights reserved.