【问题标题】:watching for variable changes during unitt esting在单元测试期间观察变量变化
【发布时间】:2020-03-11 13:27:02
【问题描述】:

我正在开发一个主要在 onNgInit() 方法上完成其工作的组件:

      stage = '';
      onNgInit(){
      const thus : any = this;
      this.stage = "start';
      this.uniService.dataExists().then(result=>{
       // the data exists. get ProductTypes
       that.stockService.productTypes().subscribe(proTypes=>{

        vm.stage = "Setting status to products";
        proTypes.map(product....);
      });
     });
    }

现在在我的测试中,我相信,因为代码是 onNgInit,stage 的值仍然是“start”。我想知道是否有办法观察变量的值变化,或者更好的是,特定变量的最终值?

import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { TrackerComponent } from "./tracker.component";

describe("TrackerComponent", () => {
  let component: TrackerComponent;
  let fixture: ComponentFixture<TrackerComponent>;

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

  beforeEach(() => {
    fixture = TestBed.createComponent(TrackerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  //
  it("should is created", () => {
    expect(component).toBeTruthy();
    expect(component.stage).toEqual('start');// want to track the changes

  });

});

【问题讨论】:

  • 你必须在断言之前调用component.onNgInit
  • 我真的不明白你想做什么/问题是什么。你能改写这篇文章吗?
  • @user3875919: fixture.detectChanges 触发组件的变更检测循环并隐式调用其ngOnInit 方法,无需再次显式调用。
  • 我以为这不是ngOnInit,而是onNgInit

标签: angular jasmine angular-unit-test


【解决方案1】:

我真的不明白你为什么在它的 ngOnInit 时调用它 onNgInit 但这里假设它是一个类型的答案:

你需要重写一点你的 ngOnInit 来返回某种值。

  public async ngOnInit(): Promise<void>{
      const thus : any = this;
      this.stage = "start';
      const result = await this.uniService.dataExists();
       // the data exists. get ProductTypes
      const proTypes = await (that.stockService.productTypes().toPromise());
      this.stage = "Setting status to products";
      proTypes.map(product....);
  }

所以在你的 UT 中你可能会有这样的东西:

 it("should is created", (done) => {
    expect(component.stage).toEqual('start');
    component.ngOnInit().then(() =>{
        expect(component.stage).toEqual('Setting status to products');          
        done();
    });
  });

要么这样,要么从 Promise 切换到 observables。

此外,您不应该只相信功能会执行。测试时,您应该测试每个停止点及其进展。

【讨论】:

    【解决方案2】:

    在使用exec 检查条件之前,您需要同步对uniService.dataExists().thenstockService.productTypes().subscribe 的异步调用。这可以在第二个beforeEach 函数中使用fakeAsyncflush 来完成。

    import { fakeAsync, flush } from '@angular/core/testing';
    ...
    beforeEach(fakeAsync(() => {
        fixture = TestBed.createComponent(TrackerComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        flush();
    }));
    

    【讨论】:

      猜你喜欢
      • 2010-10-09
      • 2016-08-05
      • 1970-01-01
      • 2021-02-14
      • 2019-08-10
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多