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

Angular unit testing - change component variable inside the test

我想测试按钮的功能,但该元素在页面上不可见,因为它在 *ngIf 下。我想将 *ngIf 中的变量设置为 truthy 以便能够显示数据。我尝试这样做:

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

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

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

问题是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();
        });
    
  });