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

时间:2020-04-08 15:53:37

标签: angular unit-testing karma-jasmine

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

2 个答案:

答案 0 :(得分:1)

更改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();
});

我创建了一个完整的测试,它对我有用

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { TestTComponent } from './test-t.component';
import { By } from '@angular/platform-browser';

fdescribe('TestTComponent', () => {
  let component: TestTComponent;
  let fixture: ComponentFixture<TestTComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [TestTComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestTComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
    component.currentUser = true;

    fixture.detectChanges();

    const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
    expect(menuDebugElement).toBeTruthy();
  });
});

答案 1 :(得分:0)

问题出在fixture.detectChanges();触发更改检测周期,当您从html组件读取值尚未完成更新时触发。

您可以使用“ whenStable()”函数来解决

  it('should open the menu when the button menu is clicked', () => {
    const fixture = TestBed.createComponent(HeaderComponent);
    component.currentUser = true;

    fixture.detectChanges();

    fixture.whenStable()
        .then(() => {
            const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
            expect(menuDebugElement).toBeTruthy();
        });
    
  });